The Whiz of Oz
The Whiz of Oz

Reputation: 7043

Query 'any' value with 'where' in Rails

I have the following method:

def self.fetch_by_subcat(subcat_id, state)
  where(state: state).joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
end 

The problem is that if my state is blank, I get back an empty array. So I would like to set my state argument to a default, something like 'any', which will simply skip the where(state ...) query and go straight to joins. So something like

def self.fetch_by_subcat(subcat_id, state='any')
  where(state: state).joins...
end 

Is there a way? Trying to avoid if/else.

Upvotes: 2

Views: 2505

Answers (2)

Marcin Raszkiewicz
Marcin Raszkiewicz

Reputation: 51

There is another way of doing it:

def self.fetch_by_subcat(subcat_id, state = 'state')
  joins(:subcategories).where("subcategory_id = ? AND published = ? AND state = #{state}", subcat_id, true)
end

How it works? If You pass state, then its simply inserted. If not the query will look like: WHERE table_name.state = table_name.state. Which is always true.

the ONLY thing to add here is to secure this method from sql injection and pass only specific, allowed state values.

Upvotes: 0

mbillard
mbillard

Reputation: 38852

You can build scopes like this:

def self.fetch_by_subcat(subcat_id, state)
  scope = joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
  scope = scope.where(state: state) unless state.blank?
  scope
end

Upvotes: 6

Related Questions