h-lame / parental_control

A plugin for rails that allows has_one, has_many and certain belongs_to associations to share instances of the "parent" model to the "child" model via the association.
MIT License
30 stars 7 forks source link

reflect_on_all_associations called on non-ActiveRecord object in some situations #5

Closed jackdempsey closed 14 years ago

jackdempsey commented 14 years ago

I've created an example app here: http://github.com/jackdempsey/parental_example/tree/master

Basically, if you have an association of a has_many and a belongs_to object, and then try to use fields_for :belongs_to_model in the new.html.erb for items in this case, you'll see that set_reciprocal_instance is called on the value sent into the controller.

I think a simple guard clause to return if we're not dealing with an AR object would be a nice and simple way to prevent this and other random edge case errors.

Adding in the error stack trace for reference:

NoMethodError in ItemsController#create

undefined method `reflect_on_all_associations' for HashWithIndifferentAccess:Class

RAILS_ROOT: /Users/jack/parental_example Application Trace | Framework Trace | Full Trace

/Users/jack/parental_example/vendor/plugins/parental_control/lib/parental_control.rb:22:in set_reciprocal_instance' /Users/jack/parental_example/vendor/plugins/parental_control/lib/parental_control.rb:53:inreplace' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/associations.rb:1258:in product=' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:2745:insend' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:2745:in attributes=' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:2741:ineach' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:2741:in attributes=' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:2439:ininitialize' /Users/jack/parental_example/app/controllers/items_controller.rb:43:in new' /Users/jack/parental_example/app/controllers/items_controller.rb:43:increate'

h-lame commented 14 years ago

Hi Jack,

Check out the new version, I think that'll fix it. Although, unless I'm mistaken, all you're doing is swapping one error (NoMethodError) for another (ActiveRecord::AssociationTypeMismatch), as you're not supposed to be able to assign a non-AR object to an association. At least we're restoring the default AR behaviour though, which is no bad thing.

jackdempsey commented 14 years ago

Great, thanks, will check it out!