2017-06-20 11 views
0

私は、別のモデルに関連付けられているすべてのインスタンスを取得する、名前付きスコープをモデルに書き込もうとしています。これは私が私がAnswer.with_templateを行うとEmailTemplateRails 5名前付きスコープ(ポリモーフィック)、UndefinedColumn

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 

ですべてのインスタンスを取得するために、スコープが必要なモデルである、このエラーが表示されます。

[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) } 

答えて

1

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

EmailTemplatetemplateable_idないAnswerを有するべきです。ですから、モデルに参加し、これが

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

を動作するはずです、彼らに

を問い合わせる必要がありますあなたは私のこと、何私は自分の答えに投稿したの違いを教えてもらえますか? –

+0

@PedroAdameVergara The * where * – Pavan

+0

申し訳ありませんが、私はなぜ私の期待どおりに動作し、私はあなたのソリューションを使用する必要があります完全に理解していません。あなたはそれを説明できますか? –

0

私は解決策を見つけました。気づいたwhereは、独自の属性で動作します。 多型の関連 1として

scope :with_template, -> { joins(:email_template) } 
関連する問題