guilb
guilb

Reputation: 123

cant update a record with rails 4

I would like update a record in my controller. I tried with save or update_attributes, but it doesnt work.

My code is :

  @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id)
  puts @relation.inspect
  @relation.save  

puts relation.inspect bring me the good object but. I got this message

NoMethodError (undefined method `save' for #<ActiveRecord::Relation::ActiveRecord_Relation_Relation:0x007fe6d6872fe8>):

I've the same problem with "update_attributes".

I 've 3 models : User , Realtor and Relation. I use "has_many :through" for create the link between User an Realtor through Relation.

My goal is to add relation.status = "something" before saving. When i add @relation.status = "test", i get :

NoMethodError (undefined method `status=' for #<ActiveRecord::Relation []>):
i think, it's a stupid error, but i cant solve it :)

I'm not in User, Realtor or Message controller but in another controller (message controller)

Thanks for advance

Upvotes: 0

Views: 74

Answers (3)

Dudo
Dudo

Reputation: 4169

Just to give you some insight on why that is... if you don't already know now.

.where() responds with an array - every time. Even if there is only 1 result, it's still in an array, so it's not an instance of your model. .find() responds with an object.

So with .where() you can use take, or .where(...).first -or- .take -or- [0].

With .find(params[:id]), it's going to be a bit more succinct, and just return the record you're looking for, or error if it doesn't it exist. .where() won't error if it can't find what you're looking for. That's something else to keep in mind.

Upvotes: 0

guilb
guilb

Reputation: 123

I find the answer...

I use : @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id).take

instead of : @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id)

Upvotes: 0

nikolayp
nikolayp

Reputation: 17949

@relation = Relation.find(params[:id])
@relation.users.create(current_user) #or build and then .save

Upvotes: 1

Related Questions