ChrisWesAllen
ChrisWesAllen

Reputation: 4975

Rails - How do i update a records value in a join model?

I have a join model in a HABTM relationship with a through association (details below). I 'm trying to find a record....find the value of that records attribute...change the value and update the record but am having a hard time doing it.

The model setup is this>>

User.rb

 has_many :choices
 has_many :interests, :through => :choices

Interest.rb

 has_many :choices
 has_many :users, :through => :choices

Choice.rb

 belongs_to :user
 belongs_to :interest

and Choice has the user_id, interest_id, score as fields.

And I find the ?object? like so >>

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id)

So the model Choice has an attribute called :score. How do I find the value of the score column....and +1/-1 it and then resave?

I tried

 @choice.score = @choice.score + 1 
 @choice.update_attributes(params[:choice])
 flash[:notice] = "Successfully updated choices value."

but I get "undefined method score"......What did i miss?

Upvotes: 1

Views: 600

Answers (3)

Max Williams
Max Williams

Reputation: 32955

You already have the @user object, so use that:

@choice = @user.choices.find_by_interest_id(interest.id)

Upvotes: 1

DanneManne
DanneManne

Reputation: 21180

Your query will return a collection of choices so you need specify .first to get hold of the actual model to update. And before you update, always check to see if you actually got hold of any object so you don't try to update nil :)

Additionally, if you only want to increase or decrease a field then you can use the methods .increment! or .decrement! which will update to database immediately.

@choice.increment!(:score)

Because in your case, if params[:choice] contains a score value, it will overwrite the value you assigned previously.

Upvotes: 2

markquezada
markquezada

Reputation: 8535

You probably need to use .first to run the actual query and return a result:

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id).first

... otherwise @choice only holds an Active Relation object... it hasn't executed the query yet.

Upvotes: 3

Related Questions