我有一个协会:
作者有很多书;
一本书有很多作者;
我需要使用:through选项(通过名为'relations'的表,有两个名为'left_id'的列(用作author_id)和'right_id'(用过ad book_id);
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'这样的选项?)
答案 0 :(得分:0)
我不知道foreign_id并且在谷歌上找不到任何东西。怎么样?
has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'
答案 1 :(得分:0)
您还应该在Relation模型中使用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