eg141840
eg141840

Reputation: 57

ruby on rails: controller can't access newly added record

I'm quite new to RoR. At first I used a sqlite3 database but migrated it to mysql. Everything worked fine with my application until I added a record to my database.

I can update my new records using the "irb" console. I have a function in my controller that is called from a python script which updates a record.

Here's the function:

# GET /dd_bots/update
# param name, att
def update
   obj = Object.all
   obj = obj.select{ |o| o.name == params[:name] }
   obj[0].update_attribute(:att, params[:att])
head :ok
end 

However this function doesn't update the newly added records returning this error: NoMethodError (undefined method update_attribute' for nil:NilClass)

Obviously the record doesn't seem to be found...

Do you have any clue why is this happening?

Upvotes: 1

Views: 153

Answers (2)

Jon Cairns
Jon Cairns

Reputation: 11951

Firstly, don't call your model Object: this could have disastrous consequences, as Object is the base class for practically every object in Ruby.

Secondly, the update_attribute is being called on the first element of obj, which is an array. You will get that error if the array contains no elements, i.e. if there are no objects where the name is the same as the name parameter being passed to the controller.

You can do this in a way that's less error prone:

def update
  obj = Object.find_by_name(params[:name])
  obj.update_attribute(:att, params[:att]) if obj
  head :ok
end

If a record should exist, you might like to throw an exception if it doesn't. You can do this by adding a ! to the find_by_name method:

obj = Object.find_by_name!(params[:name]) # Could throw an ActiveRecord::RecordNotFound

This has the benefit of giving a HTTP 404 status code if the record doesn't exist, but acts in the same way otherwise.

Upvotes: 4

kiddorails
kiddorails

Reputation: 13014

This is the conventional way of doing that. Do substitute Object with your model name.

def update
  obj = Object.find_by_name(params[:name]
  if obj
    obj.update_attribute(:att, params[:att])
  end
  head :ok
end

Does that work for you?
If not, try this in erb - Object.find_by_name('whatever_name') and see if your record actually exists or not.

Upvotes: 1

Related Questions