Jeevan Dongre
Jeevan Dongre

Reputation: 4649

undefined method `update_attribute' for ActiveRecord::Relation

I was trying to update a record in the database using Object.update_attributes(:field => "parameter") To show a simple example of what I was trying to do is this. Please see the code below

a = params["ORDERNO"].to_s
b =  params["TRACKNO"].to_s    
@bd=Staging.where(:trackno => b , :orderno=> a)
    if @bd.nil? 
       puts "not found"
    else
       @bd.update_attributes(:field_name => "PARAMETER")
    end

I also tried @bd.first.update_attributes(::field_name => "PARAMETER")

Upvotes: 1

Views: 6719

Answers (3)

Jeevan Dongre
Jeevan Dongre

Reputation: 4649

A possible solution for this

use update_all(:field_name => "PARAMETER")

Upvotes: 10

Abid
Abid

Reputation: 7227

If you know that there is only one staging correpsponding to (trackno, orderno) You can try something like this

@bd =Staging.find_by_trackno_and_orderno(b,a)
if @bd
  @bd.update_attributes(:field_name => value)
else
  #whatever you want to do
end

Upvotes: 3

Hck
Hck

Reputation: 9167

Your query @bd=Staging.where(:trackno => b , :orderno=> a) returns an array of objects.

Array usually doesn't have #update_attributes method. So you need to rewrite your query to fetch only 1 object or iterate through all the objects in the query result using each: @bd.each{|r| r.update_attributes(:field_name => "PARAMETER")}

But iterating isn't the right way to update many records, because it calls update query for each object you want to update.

Upvotes: 2

Related Questions