Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 809
user2732663 Avatar asked May 18 '26 03:05

user2732663


1 Answers

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.

like image 181
MrYoshiji Avatar answered May 20 '26 02:05

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!