首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Rails 2中使用不同的has_one关联急切地加载多态关联

在Rails 2中使用不同的has_one关联急切地加载多态关联
EN

Stack Overflow用户
提问于 2010-06-20 05:25:31
回答 1查看 1.1K关注 0票数 2

当您尝试加载一个不存在的关联时,ActiveRecord会给您一个有趣的错误。看起来是这样的:

代码语言:javascript
复制
ActiveRecord::ConfigurationError: Association named 'secondary_complaint' was not found; perhaps you misspelled it?

为什么会有人要预装一个不存在的关联呢?看看这个。

代码语言:javascript
复制
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]})

上面的代码具有有趣的特性。如果你只有Bitchy作为你的人形-它将实际工作。然而,只要一个Whiny出现-你就有麻烦了。ActiveRecord开始抱怨我上面写的错误-没有找到名为“secondary_complaint”的关联。你知道为什么吧?因为不是每个人都有secondary_complaint。

当我试图加载多态关联时,是否有一种方法可以让ActiveRecord停止抱怨和抱怨,因为多态关联可能或可能没有某些has_one关联附加到它们上?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-06-20 21:27:20

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3078315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档