简体   繁体   中英

Eager loading polymorphic associations with different has_one associations in Rails 2

ActiveRecord gives you an interesting error when you try to eager-load a non-existent association. It looks something like this:

ActiveRecord::ConfigurationError: Association named 'secondary_complaint' was not found; perhaps you misspelled it?

Now why the hell would anybody want to preload a non-existent association? Check this out.

class Bitchy < ActiveRecord::Base
  has_one :primary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'primary'}
  has_one :secondary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'secondary'}

  has_one :life, :as => :humanoid
end


class Whiny < ActiveRecord::Base
  has_one :primary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'primary'}

  has_one :life, :as => :humanoid
end

class Complaint < ActiveRecord::Base
  belongs_to :whiny_bitch, :polymorphic => true
end

class Life < ActiveRecord::Base
  belongs_to :humanoid, :polymorphic => true
end

# And here's the eager-loading part:
Life.all(:include => {:humanoid => [:primary_complaint, :secondary_complaint]})

The above code has interesting peculiarity. If you only have Bitchy as your humanoids - it will actually work. However, as soon as a single Whiny appears — you're in trouble. ActiveRecord starts whining the error I wrote above - Association named 'secondary_complaint' was not found. You see why, right? Because not every humanoid has a secondary_complaint.

Is there a way to make ActiveRecord stop bitching and whining when I'm trying to eager load polymorphic associations which may or may not have certain has_one associations attached to them?

我知道这可能只是出于示例的目的,但是您可以将其更改为has_many :complaints以便它们都具有相同的关联,然后从中提取主要或次要类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM