user2732663
user2732663

Reputation: 833

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

Upvotes: 3

Views: 18608

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

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.

Upvotes: 13

Related Questions