Hacking Active Record, how do I utilize the attributes method?
The attributes method returns a hash of all the attributes with their names as keys and the values of the attributes as values; I want to utilize this method, creating a new derivative of the update_attributes(attributes) method, lets call it jz_attributes(attributes).
开发者_如何学PythonUpdate_attributes does this:
def update_attributes(attributes)
self.attributes = attributes
save
end
And jz_attributes(attributes) will do something slightly different:
def jz_attributes(attributes)
debugger
self.attributes = attributes
#does something else
end
I want to fully utilize ActiveRecords attributes method, but I'm running into trouble:
def attributes
self.attribute_names.inject({}) do |attrs, name|
attrs[name] = read_attribute(name)
attrs
end
end
Here is what terminal is saying:
28 end
29 end
30
31 def jz_attributes(attributes)
32 debugger
=> 33 self.attributes = attributes
34 end
35
36
37 #inventory_to_increment.quantity = quantity.to_i
(rdb:1) p attributes
nil
(rdb:1) next
/Users/justinz/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:162
rescue_action(exception)
My controller that utilizes jz_attributes:
def cart2_update
@cart = find_cart
@cart.jz_attributes(params[:cart_item])
end
Do you see anything obvious that I am doing wrong? Thanks!
I recently did some very similar things when building an order form system. The order form system had to keep updating the form with changes dynamically, but I did not want to save it to the database until the user had confirmed everything. (Such as taxes, etc).
I think your on the right track, but from what you have pasted here it looks like you are trying to set nil to attributes? Maybe you can post what the params are for the request en entirety?
Assuming you are doing something similar, why not just pass attributes= ? It will not save the model, only update_attributes= should save it at this point. If you need to do something else surrounding attributes= that you want to accomplish with jz_attributes, maybe you can manipulate the parameters before they get to there, or accomplish this goal through some other means?
def cart2_update @cart = find_cart @cart.attributes=(params[:cart_item]) end
精彩评论