简体   繁体   中英

Rails don't allow attribute to update under a certain condition

Say i'm updating an attribute called status . I don't want the status to be able to be able to be updated when it's currently cancelled or complete . How could I not allow this, but allow status to be updated otherwise?

You can use a before_update callback.

   before_update :prevent_update_if_status_canceled_or_completed?

  private

  def prevent_update_if_status_canceled_or_completed?
    if status == 'canceled' || status == 'complete'
      self.errors.add_to_base "Cannot update a completed or canceled record "
      false
    else 
      true
  end
end

You can use the transitions gem . It's quite neat.

You can simply check while creating a status for that user.

def create
  @user = User.find(params[:user_id])
  unless @user.status == "cancelled" || @user.status == "completed"
    @status = @user.statuses.new(status_params)
    if @status.save!
      respond_to do |format|
        ...
        #status created logic, render desired content to user
      end
    end
  else
    #Handle status not created logic
  end
end

I guess you've a update method like:

def update
  params[:model_name].delete :status if @model_name.status == "cancelled"
  @model_name = @model_name.update(model_params) # model_params are the parameters you're allowing with strong parameters.
  .....
end

Delete the status from the strong parameter with a conditional statement.

or, you can create a private method for excluding the status from being updated.

def except_satatus_params
  params[:model_name].except(:status)
end

then use this method on the controller with a check that if @model.status is previously cancelled or complete .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM