update_attributes question

Can anyone help with this (I'm a novice). I am trying to update several attributes in the History table from inside another controller (Drill controller)

if !(History.where("user_id = ? AND question_id = ?", current_user.id, play_list[0][0])).empty?      row_to_update = History.where("user_id = ? AND question_id = ?", current_user.id, play_list[0][0])      row_to_update.update_attributes(:date_time => Time.now, :correct => params[:answeredCorr) else       ...

I get the error: NoMethodError: undefined method `update_attributes' for #<ActiveRecord::Relation::ActiveRecord_Relation_History:0x00000109d80f40> from /Users/dcastellano1/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.3/lib/active_record/relation/delegation.rb:121:in `method_missing'

Thank, Dave Castellano

Your row_to_update actually is still a relation (which for most purposes behaves like an Array) rather than a single row. It may contain one or more items.

If you are sure your array only contains one item, you can do:

row_to_update = History.where(“user_id = ? AND question_id = ?”,

current_user.id, play_list[0][0]).first

BTW you can also simplify this query:

record = History.where(user_id: current_user, question_id: play_list[0][0]).first

if record record.update_attributes(…) end

Don’t need to do .empty? check because record will be nil if not found, and the if-statement will not evaluate.

.

Alternatively, if you are not sure (and don’t care) if your query has only one record or more than one, and want to update all records that match, you can use .update_all instead of .update_attributes:

records = History.where(user_id: current_user, question_id: play_list[0][0]) records.update_all(…)

Or even better record = current_user.histories.where(question_id: play_list[0][0]) But even then I suspect something looks ideal. I feel unconfortable when I see arrays of arrays. I would have expected to see a relationship of some sort between users and play_list and history.

Colin