Luigi
Luigi

Reputation: 5603

rails 4 has_many working differently for different instances of the same model

I have the following model:

class Person < ActiveRecord::Base
  has_many :friends
end


class Friend < ActiveRecord::Base
  belongs_to :person
end

The models are more complex than that, but that's the idea. Then in my rails console:

person = Person.new
person.friends
=> #<ActiveRecord::Associations::CollectionProxy []>

This seems right - The person has no friends yet since it's a new model, so it returns an empty array.

However, when I look up a person that has many friends and try to destroy them, I get this:

person = Person.where(name: 'Test')
if person
  person.friends.destroy_all
end

NoMethodError: undefined method `friends' for #<ActiveRecord::Relation::ActiveRecord_Relation_Person:0x007f9cf42741e0>

Why is the method friends undefined for one person, but not for another? I am using rails 4.0.0 and ruby 2.0.0.

Upvotes: 0

Views: 55

Answers (2)

neo-code
neo-code

Reputation: 1076

Actually it is not working differently. this is confusion because of object name you are using.

Case 1.

    person = Person.new
    person.friends

this is creating a single object so it is working fine.

Now case 2:

   persons= Person.where(name : 'test')   
   persons.each do |person|
     person.friends..destroy_all
   end

In case 2 you are getting multiple record.

Upvotes: 0

vee
vee

Reputation: 38645

Person.where returns an ActiveRecord::Relation, you are treating it as a Person object.

Try:

people = Person.where(name: 'Test')
people.each { |p| p.friends.destroy_all }

Example, for first person object:

person = Person.where(name: 'Test').first
if person
  person.friends.destroy_all
end

Upvotes: 1

Related Questions