Rails: eager load related model with condition at third model

98 views Asked by At

I am very stuck on this problem: I have next models (it's all from Redmine):

  1. Issue (has_many :journals)

  2. Journal (has_many :details, :class_name => "JournalDetails)

  3. JournalDetails

I want fetch last changing of a state of a issue: date saved in Journal model but for filter only changing state I must join to JournalDetails.

Issue.eager_load(:journals).eager_load(journals: :details)

It's work but journals have all items not only changes of state - and how I can filter only changing of state without additional query I don't know

My next try:

Issue.eager_load({:journals => :details}).where("journal_details.prop_key = 'status_id'")

In this case I don't get issues which has not changes of state.

2

There are 2 answers

6
Yury Lebedev On

This should work:

Issue.joins(journals: :details).where(details: { prop_key: "status_id" })

Or, you can merge the scope from the details model:

class JournalDetails
  scope :for_prop_key, -> (status_id) { where(prop_key: status_id )}
end

Issue.joins(journals: :details).merge(
  JournalDetails.for_prop_key("status_id")
)
0
Yury Lebedev On

To fetch all issues, which have a non null prop_key in journal details:

class JournalDetails
  scope :with_non_null_prop_key, -> { where("prop_key IS NOT NULL") }
end

Issue.joins(journals: :details).merge(
  JournalDetails.with_non_null_prop_key("status_id")
)