Wes Creations
Wes Creations

Reputation: 387

How do I check to see if specific attribute changed upon rails update method?

When I update a record, I want the program to then see if a certain attribute was updated during that update save.

Specifically, after updating the record with the params, I want the program to see if the @state_race.poll parameter changed. If it did, I want to execute another code block.

How do I check to see if certain attribute changed?

My @state_race.poll_changed? isn't working.

  def update
    @state_race = StateRace.find(params[:id])
    if @state_race.update_attributes(state_race_params)
    puts 'race updated' 
        if  @state_race.poll_changed?
          puts 'poll changed' 
        else 
        end
    else
      render('edit')
    end 
  end

Upvotes: 1

Views: 1313

Answers (2)

Zain Awais
Zain Awais

Reputation: 40

One solution if to save the current value in other variable e.g

old_poll = @state_race.poll

then after the update, you can compare the values

if (old_poll == @state_race.poll)

The second solution is to use the gem paper-trail

Upvotes: 1

Ninh Le
Ninh Le

Reputation: 1331

The problem here is you have put method poll_changed? after attributes has update successfully. To use this polling_changed I think you should you @state_race.assign_attributes(state_race_params) and update item after or rewrite like store the value attribute poll and compare it with new value after updated.

Upvotes: 1

Related Questions