为什么多态的“ has_many”关联会选择超类名称进行查询?

时间:2019-01-09 23:13:16

标签: ruby-on-rails polymorphic-associations

我在Active Record对象中具有以下多态关联

    #table_name: ledger_entries
    #ledgerable_type
    #ledgerable_id

    class LedgerEntry::MerchantAccount < LedgerEntry
      belongs_to :ledgerable, polymorphic: true
    end 

然后我有一个关联

    class Job::Cleaning < Job
      has_many :merchant_ledgers, as: ledgerable
    end

我希望查询Job::Cleaning.last.merchant_ledgers查找ledgerable_typeJob::Cleaning的分类帐条目,而不是ledgerable_type Job。代替使用实际的类,它使用父类。 在将关联声明放入Job之前,我认为将其移至Job::Cleaning可以解决问题。但它仍然存在。

这是sql日志

     [17] pry(main)> Job::Cleaning.last.merchant_ledgers.last
      Job::Cleaning Load (0.9ms)  SELECT  "jobs".* FROM "jobs" WHERE "jobs"."deleted_at" IS NULL AND "jobs"."type" IN ('Job::Cleaning') ORDER BY "jobs"."id" DESC LIMIT $1  [["LIMIT", 1]]
      LedgerEntry::MerchantAccount Load (0.7ms)  SELECT  "ledger_entries".* FROM "ledger_entries" WHERE "ledger_entries"."type" IN ('LedgerEntry::MerchantAccount') AND "ledger_entries"."ledgerable_id" = $1 AND "ledger_entries"."ledgerable_type" = $2 ORDER BY "ledger_entries"."id" DESC LIMIT $3  [["ledgerable_id", 135277], ["ledgerable_type", "Job"], ["LIMIT", 1]]
    => nil

0 个答案:

没有答案