For a one-to-many ActiveRecord association that: must the foreign_key parameter be set?

ActiveRecord has_many

and belongs_to

use both parameters :foreign_key

. If I need to use it to handle a non-standard FK column name, should I set it to parent model ( has_many

), child model ( belongs_to

), or both, or does it matter?

+1


a source to share


2 answers


You must set the option :foreign_key

on both.

Consider the following two models:

class Article < ActiveRecord::Base
  has_many :comments, :foreign_key => "articleID"
end

class Comment < ActiveRecord::Base
  belongs_to :article, :foreign_key => "articleID"
end

      

The declaration has_many

in the class Article

allows:



Article.find(12).comments  # Finds all comments with comment.articleID == 12

      

Calling a method belongs_to

in a model Comment

allows you to:

Comment.last.article       # Finds article with article.id == comment.articleID

      

As you can see, a foreign key is used in both cases. If omitted anywhere, that particular proxy will not work as expected.

+2


a source


belongs_to

Guesses the foreign key is the name of the plus association _id

.

has_one

guesses that the foreign key is the name of the containing class plus _id

.



Usually, you only need one space for a custom key.

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

      

+2


a source







All Articles