伙计们,
想确保我正确地理解这一点。并请忽略继承的情况下在这里(SentientBeing),试图转而专注于多态模型的has_many:通过关系。尽管如此,考虑以下...
Want to make sure I understand this correctly. And please disregard the case for inheritance here (SentientBeing), trying to instead focus on polymorphic models in has_many :through relationships. That said, consider the following...
class Widget < ActiveRecord::Base has_many :widget_groupings has_many :people, :through => :widget_groupings, :source => :person, :conditions => "widget_groupings.grouper_type = 'Person'" has_many :aliens, :through => :widget_groupings, :source => :alien, :conditions => "video_groupings.grouper_type = 'Alien'" end class Person < ActiveRecord::Base has_many :widget_groupings, :as => grouper has_many :widgets, :through => :widget_groupings end class Alien < ActiveRecord::Base has_many :widget_groupings, :as => grouper has_many :widgets, :through => :widget_groupings end class WidgetGrouping < ActiveRecord::Base belongs_to :widget belongs_to :grouper, :polymorphic => true end在一个完美的世界,我想,给一个Widget和一个人,做这样的事情:
In a perfect world, I'd like to, given a Widget and a Person, do something like:
widget.people << my_person
然而,当我做到这一点,我已经注意到了'斑'的'型'总是在widget_groupings空。不过,如果我到类似如下:
However, when I do this, I've noticed the 'type' of the 'grouper' is always null in widget_groupings. However, if I to something like the following:
widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person})
然后,所有的作品,因为我本来正常的预期。我不认为我见过这种情况发生非多态关联,只是想知道这是否是一些具体的事情到这个用例,或者我可能会盯着一个错误。
Then all works as I would have normally expected. I don't think I've ever seen this occur with non polymorphic associations and just wanted to know if this was something specific to this use case or if I'm potentially staring at a bug.
感谢您的帮助!
推荐答案有一个已知问题使用Rails 3.1.1,打破了这个功能。如果你有这个问题的第一次尝试升级,它被固定在3.1.2
There is a known issue with Rails 3.1.1 that breaks this functionality. If you are having this problem first try upgrading, it's been fixed in 3.1.2
您是如此接近。问题是你滥用:源选项。 :源应指向多态性belongs_to的关系。然后,所有你需要做的就是指定:SOURCE_TYPE为你想定义的关系
You're so close. The problem is you're misusing the :source option. :source should points to the polymorphic belongs_to relationship. Then all you need to do is specify :source_type for the relationship you're trying to define.
此修复程序的窗口小部件模型应该让你做你正在寻找什么。
This fix to the Widget model should allow you do exactly what you're looking for.
class Widget < ActiveRecord::Base has_many :widget_groupings has_many :people, :through => :widget_groupings, :source => :grouper, :source_type => 'Person' has_many :aliens, :through => :widget_groupings, :source => :grouper, :source_type => 'Alien' end更多推荐
ActiveRecord的,的has
发布评论