Rails 从多态模型中加入或预加载 own_to 关联
我的问题如下。我怎样才能从多态模型加入belongs_to关联
有情况
opinion.rb
class Opinion < ActiveRecord::Base
belongs_to :opinionable, :polymorphic => true
belongs_to :category
end
answer.rb
class Answer < ActiveRecord::Base
has_many :opinions, :as => :opinionable
end
我该怎么做以下
Opinion.joins(:opinionabe).all
它会抛出
ArgumentError:如果不指定多态类,则无法创建多态Belongs_to连接!
我如何具体说明我想加入哪个班级?
第二个问题。如何预加载呢?
Opinion.preload(:opinionable).all
工作正常。它将对belongs_to中的每个类进行查询。
但。如果我想做类似的事情
Opinion.preload(:opinionable => :answer_form).all
存在问题,因为一个模型具有这种关联,而第二个模型没有。所以它会抛出异常。
那么我怎样才能做类似的事情
Opinion.preload(:answer => :answer_form, :another_belongs_to_model).all
?
谢谢,大卫!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实上,如果你这样做
,你就可以做到
Actually if you just do
then you can do
您似乎尚未为意见模型指定
opinionable_type:string
列。尝试以这种方式更新您的迁移:
这将解决您的第二个问题,并且
Opinion.preload(:opinionable).all
应该可以正常工作。您无法对多态关联进行联接,因为它们可能位于不同的表中,这些表是在加载
Opinion
模型后检测到的。这就是为什么模型需要列opinionable_type
。如果你尝试这样做,你会得到下一个异常
UPD:添加了魔法连接 ^_^
示例:
It looks like you have not specified
opinionable_type:string
column for your Opinion model.Try to update your migration in this manner:
This will solve your second question and
Opinion.preload(:opinionable).all
should work well.You cann't do joins on polymorphic association because they can be located in different tables, which are detected after
Opinion
model is loaded. That why model needs columnopinionable_type
.If you try to do this you'll get next exception
UPD: Added magic join ^_^
Example:
我知道这个问题已经很老了,但我只花了一个小时寻找类似问题(Rails 3)的解决方案,而我让它工作的唯一方法是这里所述的解决方案:https://stackoverflow.com/a/25966630/6878997
在你的情况下是:
看起来很棘手,但这样你就可以进行多个链式连接,例如:
加入(答案::other_model)
。只要
opinion.opinionable
不是Answer
,opinion.answer
就会返回nil
。希望它对某人有帮助!
I know this question is old but I just spent an hour looking for the solution to a similar problem (Rails 3) and the only way I got it to work was the solution stated here: https://stackoverflow.com/a/25966630/6878997
Which, in your case would be:
Seems tricky but this way you will be able to do multiple chained joins such as:
joins(answer: :other_model)
.And whenever
opinion.opinionable
is not anAnswer
,opinion.answer
will returnnil
.Hope it helps somebody!