Rails: Update model attribute without invoking callbacks

后端 未结 10 1588
萌比男神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:26

    To update multiple attributes without callbacks you can use update_all in your model as so:

    self.class.update_all({name: value, name: value}, self.class.primary_key => id)
    

    If you really want you can even try even a update_columns method and mixin this to your active record base class.

    To update one attribute you can use update_column. In addition there is some specific methods that can found in the rails guides http://guides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks

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

    You have a number of options, including changing which callback you use, e.g., after_create.

    You can update columns without triggering callbacks, see Skipping Callbacks in the AR guide. For example, update_column doesn't trigger callbacks. The previous link lists non-triggering functions.

    You could also use any of the Conditional Callback forms (or even an observer) for when the password is changed. See ActiveModel::Dirty, e.g., @user.password_changed?.

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

    You should be able to use update_all to avoid triggering callbacks.

    def add
     @user = User.find(params[:id])
     User.where(:id=>@user.id).update_all(:credits => @user.credits+5)
     redirect_to root_path
    end
    

    I'd prefer to put this logic in the model, but this should work to solve your original problem as spec'd in the controller.

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

    A few options for how to do this in rails4 http://edgeguides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks

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

    You can update a column doing this

    User.where( name: 'lily' ).update_all(age: '10')

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

    As a general answer, in Rails 4 this is a simple way to update attributes without triggering callbacks:

    @user.update_column :credits, 5
    

    If you need to update multiple attributes without triggering callbacks:

    @user.update_columns credits: 5, bankrupt: false  
    

    There are other options here in the Rails Guides if you prefer, but I found this way to be the easiest.

    0 讨论(0)
提交回复
热议问题