For a one-to-many ActiveRecord association that: must the foreign_key parameter be set?
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.
a source to share
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
a source to share