Skip to content

Instantly share code, notes, and snippets.

@davidlfox
Last active August 29, 2015 14:03
Show Gist options
  • Save davidlfox/405ac6e8ea087697b545 to your computer and use it in GitHub Desktop.
Save davidlfox/405ac6e8ea087697b545 to your computer and use it in GitHub Desktop.
need AR query for null parent field or non-null parent field and no related child records
def search
@chores = Chore.available
if search_params[:search_text]
@chores = @chores.where('description LIKE ?', "%%%s%" % search_params[:search_text])
elsif search_params[:zipcode]
@chores = @chores.where('location LIKE ?', "%%%s%" % search_params[:zipcode])
end
@chores = @chores.order(created_at: :desc).all
render 'index'
end
Chore Load (0.2ms) SELECT "chores".* FROM "chores" INNER JOIN "taken_chores" ON "taken_chores"."chore_id" = "chores"."id" WHERE (NOT (deadline is not null)) AND (description LIKE '%keyword%') ORDER BY "chores"."created_at" DESC
class Parent < ActiveRecord::Base
has_many :children
scope :available, -> { joins(:taken_chore).where.not('deadline is not null', :taken_chores => { :chore_id => !nil })}
end
select * from chores
where chores.deadline is null
OR (chores.deadline is not null AND
(select count(*) from taken_chores where taken_chores.chore_id=chores.id) = 0)
order by chores.created_at desc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment