ruby-on-rails – 在rails关联中使用foreign_key has_many

有人可以解释一下我的代码是否正确.

我正在尝试在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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...