开发者

updating an attribute to nil

I need to update an attribute as nil if the passed param 开发者_开发问答is the same.

For example type attribute can hold the integers say 1,2,3 if from the view I receive params[:type] as 1 and the type is also 1 I need to make it as nil.


@my_obj = MyObject.find(params[:id])

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


Actually the best way to do this is 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 the repetition of params[:your_object] -> that should be refactored)

You could also want to do it in two steps: first extract the type, and later update the attributes, but i think it is more work.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜