微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐