2

私には協会があり
ます。著者にはたくさんの本があります。そして本には多くの著者がいます。
:throughオプションを使用する必要があります(「relations」という名前のテーブルを介して、「left_id」(author_idとして使用)および「right_id」(adbook_idとして使用)という名前の2つの列があります。


class Relation < ActiveRecord::Base
  belongs_to :books
  belongs_to :authors
end

class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => 'left_id'
  has_many :books, :through => :relations
end

コンソールの場合:


> author = Author.new
> author.books 
#  => Error: no such column: relations.book_id

では、どうすれば「book_id」を「right_id」に指定できますか?(「foreign_key」のようなオプションはありますか?)

4

2 に答える 2

0

関係モデルでもforeign_keyを使用する必要があるため、belongs_toにもforeign_keyがあります。より具体的には、これが必要なものです:

class Relation < ActiveRecord::Base
  belongs_to :book, :foreign_key => :left_id
  belongs_to :author, :foreign_key => :right_id
end

他のモデルは次のようになります。

class Book < ActiveRecord::Base
  has_many :relations, :foreign_key => :left_id
  has_many :authors, :through => :relations
end


class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => :right_id
  has_many :books, :through => :relations
end
于 2010-08-14T09:51:22.577 に答える
-1

私はforeign_idについて知りません、そしてグーグルで何も見つけることができません。これはどう?

has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'
于 2010-08-14T07:21:47.590 に答える