has_one关联独立工作但在范围内使用时不返回任何内容

时间:2015-11-24 20:23:37

标签: ruby-on-rails activerecord scope associations

我知道这不是最小的问题,但请耐心等待 - 我想我会错过一些东西,但无法弄清楚是什么。

class Company::ExpositionTarget::DiscretionaryNote < ActiveRecord::Base
  belongs_to :company_exposition_target,
    class_name: ::Company::ExpositionTarget
end

class Company::ExpositionTarget < ActiveRecord::Base
    has_many :discretionary_notes,
      class_name: ::Company::ExpositionTarget::DiscretionaryNote,
      foreign_key: :company_exposition_target_id

    has_one :last_discretionary_note,
      ->(exposition_target) { where(company_exposition_target: exposition_target).order(created_at: :desc).limit(1) },
      class_name: ::Company::ExpositionTarget::DiscretionaryNote,
      foreign_key: :company_exposition_target_id
end

每个定义的关联都可以100%运行。我们感兴趣的是has_one :last_discretionary_note

Company::ExpositionTarget.find(102).last_discretionary_note

生成的SQL:

  SELECT  company_exposition_targets.*
  FROM company_exposition_targets
  WHERE company_exposition_targets.id = 102
  LIMIT 1

  SELECT company_exposition_target_discretionary_notes.* 
  FROM company_exposition_target_discretionary_notes 
  WHERE company_exposition_target_discretionary_notes.company_exposition_target_id = 102 
  AND company_exposition_target_discretionary_notes.company_exposition_target_id = 102
  LIMIT 1

返回预期结果 - last discretionary_note。

我最初需要的是:

按最后一项自由裁量权注意事项 排序exposition_targets

要进行排序,我想创建一个范围:

scope :discretionary_notes_available, ->(true_false) {
  joins(:last_discretionary_note)# more data selection based on true_false
}

现在问题是:

Company::ExpositionTarget.joins(:last_discretionary_note) 不返回任何内容

生成的SQL:

  SELECT company_exposition_targets.*
  FROM company_exposition_targets
  INNER JOIN company_exposition_target_discretionary_notes
  ON company_exposition_target_discretionary_notes.company_exposition_target_id = company_exposition_targets.id 
  AND company_exposition_target_discretionary_notes.company_exposition_target_id = NULL

此查询错误,未考虑has_one: last_discretionary_note的定义。

问题:

为什么AR没有在范围内正确处理has_one关联?而且,更重要的是 - 我的错误在哪里以及如何实现我的需求?

再次,示意性地我需要以下内容:

scope :discretionary_notes_available, ->(true_false) {
  select all company_exposition_targets where company_exposition_targets.discretionary_notes.last.allow_participant_to_download_pdf = true_false
}

0 个答案:

没有答案