
我正在尝试在rails关联中获取foreign_key选项.
我有2个型号:
书和作者
预订数据库模式:
>名字
> user_ID
作者db schema:
>名字
我的模特:
class Author < ApplicationRecord has_many :books,foreign_key: :user_IDendclass Book < ApplicationRecord belongs_to :author,foreign_key: :user_IDend
在这里,我不明白为什么我们应该在两个模型中定义foreign_key.这是必然的吗?
解决方法 如果您已经使用了Rails期望的表名和列名,那么您不需要显式定义foreign_key.在您的情况下,如果外键列名为author_ID,那么您可以非常简单地得到:class Author < ApplicationRecord has_many :booksendclass Book < ApplicationRecord belongs_to :authorend
但是,在您的情况下,外键列不是根据Rails期望的名称命名的,因此您需要显式定义外键列名.这很好,但它确实为你做了一些工作.
如果您已明确定义外键,则应为两个关联定义它.没有它,你的has_many协会将无法运作.
此外,您应该定义反向关联:
class Author < ApplicationRecord has_many :books,foreign_key: :user_ID,inverse_of: :authorendclass Book < ApplicationRecord belongs_to :author,inverse_of: :booksend
定义inverse_of可以使ActiveRecord减少查询次数,并消除一些意外行为.有关inverse_of的解释,请参阅Ryan Stenberg的Exploring the :inverse_of Option on Rails Model Associations
以上是内存溢出为你收集整理的ruby-on-rails – 在rails关联中使用foreign_key has_many全部内容,希望文章能够帮你解决ruby-on-rails – 在rails关联中使用foreign_key has_many所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)