I'm trying to write a named scope in my model that retrieves all instances that are associated with another model. This is the model where I need the scope to retrieve all instances with EmailTemplate
class Answer < ApplicationRecord
has_one :email_template, as: :templateable
validates :text, presence: true
scope :with_template, -> { where.not(email_template: nil) }
end
And my other model
class EmailTemplate < ApplicationRecord
belongs_to :templateable, polymorphic: true
validates :pre, presence: true
validates :post, presence: true
end
When I do Answer.with_template
, this error shows up.
[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'
Tried with this too, and doesn't work:
scope :with_template, -> { where.not(templateable: nil) }
答案 0 :(得分:1)
ActiveRecord :: StatementInvalid:PG :: UndefinedColumn:ERROR:no existe la columna answers.templateable
根据多态关联,EmailTemplate
应该是templateable_id
而不是Answer
。所以你应该加入模型并查询它们
这应该有效
scope :with_template, -> { includes(:email_template).where.not("email_templates.templateable_id IS NULL") }
答案 1 :(得分:0)
我刚刚找到了解决方案。注意到dataType: "json"
使用自己的属性。
where