IulianWasHere
IulianWasHere

Reputation: 45

When using has_many with custom foreign_key i get an undefined method error, in Rails 3

The first model:

class FaqGroup < ActiveRecord::Base
  has_many :faqs, :foreign_key => 'group_id', :order => 'position'

  acts_as_list
end

The second model:

class Faq < ActiveRecord::Base
  belongs_to :faq_group, :foreign_key => 'group_id'

  acts_as_list :scope => :faq_group
end

The controller:

def new_faq
  @group = FaqGroup.find(params[:id])

  @faq = @group.faqs.create(question: 'lorem', answer: 'ipsum')

end

When i load that in the browser I get the following error:

undefined method `faq_group_id' for #<Faq:0xb56fcde4>

So, basically when I try to create a new associated object, the foreign_key just gets ignored. If i give up the custom :foreign_key everything works great.

Another observation would be that if I do:

@group = FaqGroup.find(params[:id])
@faqs = @group.faqs

it WORKS ok, so it seems that it has problems using the foreign_key only when it creates new associated objects.

Thank you!

Upvotes: 1

Views: 1298

Answers (1)

sjain
sjain

Reputation: 23344

Check the belongs_to association with the foreign key option.

As mentioned there,

For foreign key in belongs_to-

"Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a belongs_to :person association will use “person_id” as the default :foreign_key. Similarly, belongs_to :favorite_person, :class_name => "Person" will use a foreign key of “favorite_person_id”."

So in context with it, the error is because you defined:

class Faq < ActiveRecord::Base
  belongs_to :faq_group, :foreign_key => 'group_id'

This association requires faq_group_id as the foreign key and not the group_id.

So is the error -

undefined method `faq_group_id' for #<Faq:0xb56fcde4>

Upvotes: 1

Related Questions