简体   繁体   中英

Update params in Ruby on Rails controller

I have a controller in which I want to update the value of one of the parameters before the update so that the update is carried out in the same save to the database. Unfortunately, the following code does not set z in the database:

if @model.x == "YES" && @model.z.blank? 
   model_params[:z] = Time.now
end
@model.update_attributes(model_params) 

def model_params
  params.require(:model).permit(:x, :y, :z)
end

This should do it:

def update
  attributes = model_params.clone
  if @model.x == "YES" && @model.z.blank?
    attributes[:z] = Time.now
  end
  @model.update_attributes(attributes)
end

def model_params
  params.require(:model).permit(:x, :y, :z)
end

You code did not work on the first place because calling model_params calls the method, not the actual local variable. You need to create a clone of the returned Hash and use it for the update_attributes.

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