简体   繁体   English

在嵌套多态关联中使用包含

[英]Using includes with nested polymorphic association

I am working on a Rails 5 project and have a model called Upvote that is polymorphic and belongs to either an Event or Suggestion. 我正在一个Rails 5项目上工作,并且有一个名为Upvote的模型,该模型是多态的,属于Event或Recommendation。 I am trying to specifically grab upvotes that belong to one category or the other as well as the user id of whoever created the event/suggestion, but am struggling because of the polymorphism. 我试图专门抓住属于一个类别或另一类别的upvotes,以及创建事件/建议的人的用户ID,但是由于多态性而苦苦挣扎。 There was a similar post on this a few years ago, but when I tried implementing the technique it didn't work. 几年前也有类似的帖子 ,但是当我尝试实现该技术时,它不起作用。 Specifically, I added this code to my Upvote model: 具体来说,我将此代码添加到了我的Upvote模型中:

belongs_to :suggestion, -> { where(upvotes: {idea_type: 'Suggestion'}) }, foreign_key: "idea_id"

but when I try something like 但是当我尝试类似

Upvote.includes(:suggestion).last

in the console I get this error: 在控制台中,我得到此错误:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "upvotes"
LINE 1: SELECT "suggestions".* FROM "suggestions" WHERE "upvotes"."i...

Can anyone please help? 谁能帮忙吗? Thanks :) 谢谢 :)

On Rails5, belongs_to has an required: true clause by default... So, it always checks if the counter parts exists... and there is no has_many :upvote relation on Suggestion ... 在Rails5, belongs_to有一个required: true的违约条款...所以,它总是会检查,如果计数器部分存在......并且没有has_many :upvote的关系, Suggestion ...

To don't require the counter part, you can add the option optional: true to your belongs_to clause 要不需要计数器部分,您可以添加选项option optional: true到您的belongs_to子句

belongs_to :suggestion, -> { where(upvotes: {idea_type: 'Suggestion'}) }, foreign_key: "idea_id", optional: true

OBS1 OBS1

I started a Pull Request on Rails recently just because of this question, and on this discussion we figured out that actually if you don't want that a belongs_to would be required: true by default, you can just config that behaviour setting the config: 正是由于这个问题,我最近才开始在Rails上执行Pull Request,在这次讨论中我们发现,实际上,如果您不希望需要一个belongs_to required: true默认情况下为required: true ,您可以通过设置配置来配置该行为:

Rails.application.config.active_record.belongs_to_required_by_default = false

That on fresh installs of Rails5 is set to true, but is not set for apps that where migrated to Rails5 全新安装的Rails5上的该值设置为true,但对于迁移到Rails5的应用程序未设置该值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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