Reputation: 15374
I would like to know how to successfully set out a dynamic Active Record query based on whether the params are present/exist.
I have this query
Animal.joins(:user).where(animal_type: params[:animal_type], rehomed: params[:rehomed], users: {town: params[:animal_town]})
I have tried something along these lines, but my syntax is all wrong, I believe:
conditions = []
conditions << [ animal_type: params[:animal_type], ] if params[:animal_type].present?
conditions << [ rehomed: params[:rehomed], ] if params[:rehomed].present?
conditions << [ users: {town: params[:animal_town]} ] if params[:animal_town].present?
@animals = Animal.joins(:user).where(conditions)
I don't want to put it all in a nested hash, do I?
Upvotes: 2
Views: 776
Reputation: 106792
I would do somethink like this:
scope = Animal.joins(:user)
scope = scope.where(animal_type: params[:animal_type]) if params[:animal_type].present?
scope = scope.where(rehomed: params[:rehomed]) if params[:rehomed].present?
scope = scope.where(users: { town: params[:animal_town] }) if params[:animal_town].present?
@animals = scope
Further improvements: Move building of the scope into a method in the Animal model:
# in controller
@animals = Animal.find_by_query(params.slice(:animal_type, :rehomed, :animal_town))
# in Animal model
def self.find_by_query(query = {})
query.reject { |_, v| v.blank? }
scope = joins(:user)
scope = scope.where(animal_type: query[:animal_type]) if query[:animal_type]
scope = scope.where(rehomed: query[:rehomed]) if query[:rehomed]
scope = scope.where(users: { town: query[:animal_town] }) if query[:animal_town]
scope
end
Upvotes: 2
Reputation: 3721
You have to do:
conditions = {}
conditions.merge!(animal_type: params[:animal_type]) if params[:animal_type].present?
conditions.merge!(rehomed: params[:rehomed]) if params[:rehomed].present?
conditions.merge!(users: {town: params[:animal_town]}) if params[:animal_town].present?
@animals = Animal.joins(:user).where(conditions)
Upvotes: 4