Ruby on Rails:有没有办法暂时禁用多态关联?
我在多态模型之间建立了关联。
示例:
class Review
belongs_to :review_subject, :polymorphic => true
end
但是,我想调用此 :review_subject 关联,我知道所有结果都将属于某种类型。
就我而言,我想这样做,以便我可以加入 review_subject,然后对其施加一个条件。对多态关系执行此操作通常会导致引发 EagerLoadPolymorphicError。其背后的逻辑是,它无法知道要加载哪个模型才能执行联接,但这不适用于我的情况,因为我已经知道此查询中将只涉及一个模型。
示例,我知道所有相关评论都属于一本书,并且我只想显示书籍有作者的评论:
Review.joins(:review_subject)
.where(review_subject_type => "Book")
.where("reviewed.book_author IS NOT NULL")
有没有办法暂时禁用多态关系? b>
我想出的最佳解决方案是在 Review 模型中添加第二个关联,belongs_to :review_subject_books_only
,它不是多态的,并且只能在这种情况下调用。然而,这在模型中都是一个丑陋的黑客行为,而且它还会扰乱include
调用,除非视图也引用评论的review_subject_books_only。
I've got an association between models that is polymorphic.
Example:
class Review
belongs_to :review_subject, :polymorphic => true
end
However, I would like to make a call on this :review_subject association where I know all the results will be of a certain type.
In my case, I want to do this so I can join in the review_subject and then impose a condition upon it. Doing so on a polymorphic relation normally causes this to raise an EagerLoadPolymorphicError. The logic behind this is that it's not able to know what model to load in order to perform the join, but that does not apply in my case because I already know only one model will be involved in this query.
Example, where I know that all relevant reviews will belong_to a Book, and I want to only show reviews where the books have authors:
Review.joins(:review_subject)
.where(review_subject_type => "Book")
.where("reviewed.book_author IS NOT NULL")
Is there a way to temporarily disable the polymorphic relationship?
The best solution I've come up with is to add a second associationin the Review model, belongs_to :review_subject_books_only
that is not polymorphic, and can be called on only in this situation. However, this is an ugly hack both in the model, and in that it also messes up include
calls unless the views also refer to a Review's review_subject_books_only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以相反的方式执行查询:
Do the query the other way around: