Rails: update_column works, but not update_attributes

后端 未结 3 468
被撕碎了的回忆
被撕碎了的回忆 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:08

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 20:26

    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)
    
    0 讨论(0)
提交回复
热议问题