Rails: Update model attribute without invoking callbacks

后端 未结 10 1592
萌比男神i
萌比男神i 2021-02-04 23:15

I have a User model that has a :credits attribute. I want a simple button that will add 5 to the user\'s credits, through a route called \"add\" so that /users/3/add would ad

相关标签:
10条回答
  • 2021-02-04 23:42

    Maybe your other before_save hook should check if the user's password has actually changed before encrypting it again.

    0 讨论(0)
  • 2021-02-04 23:52

    Rails 3.1 introduced update_column, which is the same as update_attribute, but without triggering validations or callbacks:

    http://apidock.com/rails/ActiveRecord/Persistence/update_column

    0 讨论(0)
  • 2021-02-04 23:52

    For mongoid, I ended up using http://mongoid.org/en/mongoid/docs/persistence.html Specifically, you can use:

    person.set(name:"Robert Pulson")
    

    and no callback will be issued. So cool.

    0 讨论(0)
  • 2021-02-04 23:53

    I think you should use the method update_counters in this case. Use it like this in your controller action:

    def add
      User.update_counters params[:id], :credits => 5
      redirect_to root_path
    end
    
    0 讨论(0)
提交回复
热议问题