开发者

Difference between update_attributes and setting to nil directly

Is there a difference between the following two snippets for this given class?

class MyObjectClass < ActiveRecord::Base
  belongs_to :address
end

# Snippet 1
my_obj.address = nil
my_obj.save

# Snippet 2
m开发者_运维问答y_obj.update_attributes {address: nil}


Behind the scenes they are essentially doing the same thing if you're talking solely about setting the address field to nil.


There is no difference between them at all. If you had used my_obj.update_attributes(params[:my_object]) then Spikes answer would be correct as you are dealing with mass assignment, however in snippet 2 you are only updating the address attribute so they are identical.


Snippet 2 is subject to mass assignment security. More details are in the Rails security guide. Snippet 2 also skips validations and callbacks.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜