Rails: update_column works, but not update_attributes

给你一囗甜甜゛ 提交于 2019-11-28 16:25:19
alestanis

The three methods you are using do different things:

  • update_attributes tries to validate the record, calls callbacks and saves;
  • update_attribute doesn't validate the record, calls callbacks and saves;
  • update_column doesn't validate the record, doesn't call callbacks, doesn't call save method, though it does update record in the database.

If the only method that "works" is update_column my guess is that you have a callback somewhere that is throwing an error. Try to check your log/development.log file to see what's going on.

You can also use update_attributes!. This variant will throw an error, so it may give you information on why your model isn't saving.

You should use update_attributes and avoid the two other methods unless you know exactly what you are doing. If you add validations and callbacks later to your model, using update_attribute and update_column can lead to nasty behaviour that is really difficult to debug.

You can check this link for more info on that.

I had this same issue, but with Rails 4. The issue happens when you have params[] in update_attribute. In Rails 4 with strong parameters

@reply.update_attributes(params[reply_params])

should be

@reply.update_attributes(reply_params)

I'm not to familiar with Rails 3 but this should be the issue:

@reply.update_attributes(params[:reply])

should be

@reply.update_attributes(:reply)
Pasta

A gut guess would be to say that you have a mass assignment problem and should add your attributes in your model like this

attr_accessible: :your_attribute, :your_attribute2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!