This project is archived and is in readonly mode.
has_one through doesn't work when going through a collection association
-
Dan Pickett
- Tag changed from 2.2.2, activerecord, alias_method, associations, has_one_through, update_attributes to 2.2.2, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes
can a bugmasher review this against master?
-
Lake
- Tag changed from 2.2.2, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes to 2.2.2, 3.0.0.beta, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes
It appears that this happens even if we don't use alias_method...
I have posted some code on github to try and help identify the issue. Check the readme for a quick overview.
-
Jeff Kreeftmeijer
- Tag changed from 2.2.2, 3.0.0.beta, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes to 2.2.2, 3.0.0.beta, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes, verified
Verified with Thomas' code snippet against master and Lake's github repo (also, master).
And here's a cleaned up version of Thomas' code:
class Foo < ActiveRecord::Base has_many :foobars has_one :bar, :through => :foobars alias_method :orig_bar=, :bar= def bar=(value) self.orig_bar = value end end class Foobar < ActiveRecord::Base belongs_to :foo belongs_to :bar end class Bar < ActiveRecord::Base endAnd run this in the console:
Foo.new.bar = Bar.new -
Jon Leighton
- Assigned user set to Aaron Patterson
- Title changed from has_one through fails when setter is overridden using alias_method to has_one through doesn't work when going through a collection association
- Tag changed from 2.2.2, 3.0.0.beta, activerecord, alias_method, associations, bugmash, has_one_through, update_attributes, verified to 2.2.2, 3.0.0.beta, activerecord, alias_method, associations, bugmash, has_one_through, patch, update_attributes
This is not actually a problem with aliases at all.
The problem is with putting a
has_oneassociation:througha collection (i.e.has_many).HasOneThroughAssociation#create_through_recordlooks up the through association, and expects it to be a single record. On this assumption it usesupdate_attributes, which obviously isn't defined on a collection. Hence the problem.My preferred solution is to make it invalid to put a
has_onethrough a collection. If the user really wants to go through an association that could have many different records, they can explicitly add ahas_onein place of thehas_many, and use a combination of:order,:conditionsetc to be specific about which record they want.I've attached a tested patch which prohibits
has_oneassociations going through collections. -
blatyo
+1 @ Jon
-
Jon Leighton
- State changed from new to resolved
