Search code examples
ruby-on-railsrubyactiveresource

ActiveResource::BadRequest error when trying to save after one update to a primitive attribute


I am currently working with a REST API that has an object with an attribute "name."

item = person.find(id)

I can loop through the item's attributes without any problem and one attribute is, indeed, "name." However, when I try the following:

item.attributes["name"] = "New Name"

I can confirm that the attribute "name" has been updated, yet after calling

item.save

results in an ActiveResource::BadRequest (400) error. Has anybody encountered a problem like this before?

Thanks!

I tried the above and I also tried

item = person.find(id)
item.name = "New Name"
item.save

Finally, per suggestion, I tried

item.update_attribute(:name, "New Name")

and omitted item.save since the save is performed inherently.

It seems that no matter what I try, I continue to see the following stacktrace:

ActiveResource::BadRequest (Failed.  Response code = 400.  Response message = Bad Request.): 
app/controllers/home_controller.rb:84:in `update_data'

Where Line 84 is the event where the ActiveResource object is being updated.


Solution

  • Looks like attributes= is deprecated on the latest stable version of Rails. The last existing version (v3.1.0).

    Instead, you can use update_attribute to update the record's attribute:

    item.update_attribute(:name, "New Name")
    

    and update_attribute will save the record (if valid), so you don't have to call save on it.