Update attribute to zero

I need to update the attribute as nilif the passed parameter is the same.

For example, an attribute typemay contain integers: 1,2,3if from the view that I get params[:type]as 1well as the type 1, I need to make it like nil.

+3
source share
2 answers
@my_obj = MyObject.find(params[:id])

if params[:type] == @my_obj.type
  @my_obj.update_attribute(:type, nil)
end
+2
source

Actually the best way to do this is with something like

params[:your_object][:test] = nil if params[:your_object][:test] == @your_object.type
@your_object.update_attributes(params[:your_object])

(simple code: see repeat params[:your_object]→ to be reorganized)

You can also do this in two steps: first extract the type and then update the attributes, but I think this works more.

received_type = params[:your_object].delete(:type)
received_type = nil if received_type == @your_object.type
@your_object.update_attribute :type, received_type

#still do the rest of the update, without the type
@your_object.update_attributes(params[:your_object])

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1790648/


All Articles