I have an issue with a conditional query I've written in a Rails application. Currently I have Stores being queried if certain locations (location_north, location_south, etc) are true and if certain types (type_dining, type_unique, etc) are true, but I instead want it to query them if any of those are two, not ALL of them are true.
For example, if the Lead has location_north and location_east set as true, I want to query all Stores with location_north OR location_east, the Store wouldn't need both set to true.
Same for the types, if a Lead has a store_type_unique true and a store_type_dining true, I want to query for all Stores that have a type_unique OR type_dining true, the Store wouldn't need both set to true.
I know there are issues with how my database is organized, but is there anyway to set this up with the current build? Thanks for any guidance, it's appreciated!
def build_filters_obj
filters = []
filters.push 'location_north' if @lead.location_north
filters.push 'location_east' if @lead.location_east
filters.push 'location_south' if @lead.location_south
filters.push 'location_west' if @lead.location_west
filters.push 'location_other' if @lead.location_other
return filters
end
def perform(lead_id)
@lead = Lead.find(lead_id)
lead_email = ValidEmail2::Address.new(@lead.email)
UserNotifierMailer.send_signup_email(@lead).deliver if lead_email.valid?
@stores = Store.all
@stores = @stores.where.not(email: [nil, ''])
n = @lead.guests_total.to_i
@stores = @stores.where("capacity_min <= ? AND capacity_max >= ?", n, n)
@stores = @stores.where(:type_unique => true) if @lead.store_type_unique
@stores = @stores.where(:type_dining => true) if @lead.store_type_dining
@stores = @stores.where(:type_hotel => true) if @lead.store_type_hotel
filters = build_filters_obj
filters.each do |filter|
@stores = @stores.where(filter.to_sym => true)
end
@stores = @stores.or(Store.where(:receive_all => true))
@stores.each do |store|
store_email = ValidEmail2::Address.new(store.email)
UserNotifierMailer.send_lead_email(store, @lead).deliver if store_email.valid?
end
end
A very quick change would be to rewrite each of these lines:
to this:
And the same for the line inside your
filtersloop.From there, write tests to make sure you're getting the correct logic. Finally, you can refactor to DRY up the code.