Rails: update_column works, but not update_attributes

后端 未结 3 471
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 19:40

I have a simple model:

class Reply < ActiveRecord::Base
  attr_accessible :body
  belongs_to :post
end

In my controller, I have a simple

3条回答
  •  春和景丽
    2020-12-12 20:18

    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.

提交回复
热议问题