有人可以解释一下我的代码是否正确.
我正在尝试在rails关联中获取foreign_key选项.
我有2个型号:
书和作者
预订数据库模式:
>名字
> user_id
作者db schema:
>名字
我的模特:
class Author < ApplicationRecord has_many :books,foreign_key: :user_id end class Book < ApplicationRecord belongs_to :author,foreign_key: :user_id end
在这里,我不明白为什么我们应该在两个模型中定义foreign_key.这是必然的吗?
解决方法
如果您已经使用了Rails期望的表名和列名,那么您不需要显式定义foreign_key.在您的情况下,如果外键列名为author_id,那么您可以非常简单地得到:
class Author < ApplicationRecord has_many :books end class Book < ApplicationRecord belongs_to :author end
但是,在您的情况下,外键列不是根据Rails期望的名称命名的,因此您需要显式定义外键列名.这很好,但它确实为你做了一些工作.
如果您已明确定义外键,则应为两个关联定义它.没有它,你的has_many协会将无法运作.
此外,您应该定义反向关联:
class Author < ApplicationRecord has_many :books,foreign_key: :user_id,inverse_of: :author end class Book < ApplicationRecord belongs_to :author,inverse_of: :books end
定义inverse_of可以使ActiveRecord减少查询次数,并消除一些意外行为.有关inverse_of的解释,请参阅Ryan Stenberg的Exploring the :inverse_of
Option on Rails Model Associations