对于ActiveRecord一对多关联,我应该设置:foreign_key选项?

时间:2009-05-13 21:48:23

标签: ruby-on-rails ruby activerecord

ActiveRecord的has_manybelongs_to方法均采用:foreign_key选项。如果我需要使用它来处理非标准的FK列名称,我应该为父模型(has_many),子模型(belongs_to)或两者设置它,还是重要?

2 个答案:

答案 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