如何使用 :through 选项声明 has_many 关联的特定键?
我有一个协会:
一个作者有很多本书; 一本书有很多作者;
我需要使用 :through 选项(通过名为“关系”的表,有两列名为“left_id”(用作author_id)和“right_id”(用作广告 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' 这样的选项吗?)
I have an association:
an author has many books;
and a book has many authors;
I need to use :through option(through a table named 'relations',has two column named 'left_id' (used as author_id) and 'right_id' (used 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
In the console:
> author = Author.new
> author.books
# => Error: no such column: relations.book_id
So, how could I specific the 'book_id' to 'right_id'?(Is there some option like 'foreign_key'?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还应该在关系模型中使用foreign_key,因此belongs_to也有foreign_key。更具体地说,这就是您所需要的:
其他模型应该是:
You should use a foreign_key also in the Relation model, so the belongs_to has also foreign_key. More specifically this is what you need:
and the other models should be:
我不知道foreign_id,在谷歌上找不到任何东西。这个怎么样?
I don't know about foreign_id and can't find anything on google. How about this?