ActiveRecord的has_many
和belongs_to
方法均采用:foreign_key
选项。如果我需要使用它来处理非标准的FK列名称,我应该为父模型(has_many
),子模型(belongs_to
)或两者设置它,还是重要?
答案 0 :(得分:2)
您应在两者上设置:foreign_key
选项。
考虑以下两种模式:
class Article < ActiveRecord::Base
has_many :comments, :foreign_key => "articleID"
end
class Comment < ActiveRecord::Base
belongs_to :article, :foreign_key => "articleID"
end
在has_many
课程中声明Article
可以执行以下操作:
Article.find(12).comments # Finds all comments with comment.articleID == 12
belongs_to
模型中的Comment
方法调用允许:
Comment.last.article # Finds article with article.id == comment.articleID
如您所见,在这两种情况下都使用外键。如果在任一位置省略,则该特定关联代理将无法正常工作。
答案 1 :(得分:2)
belongs_to
猜测外键是关联名称加_id
。
has_one
猜测外键是包含类加_id
的名称。
通常对于非标准密钥,您只需在一个地方使用它。
class Book < ActiveRecord::Base
# Rails default fk is isbn_id
belongs_to :isbn, :class_name => "BarCode", :foreign_key => "bar_code_id"
end
class BarCode < ActiveRecord::Base
# Rails default fk is bar_code_id, so you don't need to specify it
has_one :book
end