Skip to content

Instantly share code, notes, and snippets.

@channainfo
Last active August 31, 2022 02:07
Show Gist options
  • Save channainfo/4781fad1c5ec74c84a4f7fff414398f0 to your computer and use it in GitHub Desktop.
Save channainfo/4781fad1c5ec74c84a4f7fff414398f0 to your computer and use it in GitHub Desktop.
State dependencies between two or model - design / retrieval technique
def self.filter_by_job_status(job_status)
projects = where(nil)
if job_status == :completed
match_all = <<~EOD
EXISTS ( SELECT 1 FROM jobs WHERE jobs.project_id = projects.id ) AND
NOT EXISTS ( SELECT 1 from jobs WHERE jobs.project_id = projects.id AND jobs.status NOT IN (?) )
EOD
return projects.where([match_all, job_status])
end
projects.where(['EXISTS ( SELECT 1 FROM jobs WHERE jobs.project_id = projects.id AND jobs.status = ? )', job_status])
end
@channainfo
Copy link
Author

This problem happens a lot for example in Spree commerce order state and shipment state depend on each other.
When an order is first created, the order sets status to shipments. when the shipment state changes to ship, the order should be aware of all shipment states are shipped then the order state should be shipped.

Spree also stores shipment_state as a calculated field to avoid joining with the shipments table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment