Rails 5 命名范围具有多态性,UndefinedColumn

佩德罗·阿达梅·维加拉

我正在尝试在我的模型中编写一个命名范围,以检索与另一个模型关联的所有实例。这是我需要范围来检索所有实例的模型EmailTemplate

class Answer < ApplicationRecord
  has_one :email_template, as: :templateable
  validates :text, presence: true

  scope :with_template, -> { where.not(email_template: nil) }
end

还有我的另一个模型

class EmailTemplate < ApplicationRecord
  belongs_to :templateable, polymorphic: true
  validates :pre, presence: true
  validates :post, presence: true
end

当我这样做时Answer.with_template,会出现此错误。

[3] pry(main)> Answer.with_template
   (6.6ms)  SELECT COUNT(*) FROM "answers" WHERE ("answers"."templateable" IS NOT NULL)
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  no existe la columna answers.templateable
LINE 1: SELECT COUNT(*) FROM "answers" WHERE ("answers"."templateabl...
                                              ^
: SELECT COUNT(*) FROM "answers" WHERE ("answers"."templateable" IS NOT NULL)
from /home/pedro/.rvm/gems/ruby-2.4.0/gems/activerecord-5.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:620:in `async_exec'

也试过这个,但不起作用:

scope :with_template, -> { where.not(templateable: nil) }
帕万

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: no existing la columna answers.templateable

根据多态关联, theEmailTemplate应该有而templateable_id不是Answer所以你应该加入模型并查询它们

这应该工作

scope :with_template, -> { includes(:email_template).where.not("email_templates.templateable_id IS NULL") }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章