AnApprentice
AnApprentice

Reputation: 110960

Rails - Conditional Query, with ActiveRecord?

Given a query like:

current_user.conversations.where("params[:projectid] = ?", projectid).limit(10).find(:all)

params[:projectid] is being sent from jQuery ajax. Sometimes that is an integer and the above works fine. But if the use selects "All Projects, that's a value of '' which rails turns into 0. which yields an invalid query

How with rails do you say search params[:projectid] = ? if defined?

Thanks

Upvotes: 0

Views: 5235

Answers (2)

vonconrad
vonconrad

Reputation: 25377

I think you may have mistyped the query a bit. "params[:projectid] = ?" shouldn't be a valid query condition under any circumstances.

In any case, you could do some sort of conditional statement:

if params[:project_id].blank?
  @conversations = current_user.conversations.limit(10)
else
  @conversations = current_user.conversations.where("project_id = ?", params[:project_id]).limit(10)
end

Although, I'd probably prefer something like this:

@conversations = current_user.conversations.limit(10)
@converstaions.where("project_id = ?", params[:project_id]) unless params[:project_id].blank?

Sidenotes:

  1. You don't have to use .find(:all). Rails will automatically execute the query when the resultset is required (such as when you do @conversations.each).
  2. Wherever possible, try to adhere to Rails' snakecasing naming scheme (eg. project_id as opposed to projectid). You'll save yourself and collaborators a lot of headaches in the long run.

Thanks but if the where query has lets say 3 params, project_id, project_status, ... for example, then the unless idea won't work. I'm shocked that Rails doesn't have a better way to handle conditional query params

EDIT: If you have multiple params that could be a part of the query, consider the fact that where takes a hash as its argument. With that, you can easily build a parameter hash dynamically, and pass it to where. Something like this, maybe:

conditions = [:project_id, :project_status, :something_else].inject({}) do |hsh, field|
  hsh[field] = params[field] unless params[field].blank?
  hsh
end

@conversations = current_user.conversations.where(conditions).limit(10)

In the above case, you'd loop over all fields in the array, and add each one of them to the resulting hash unless it's blank. Then, you pass the hash to the where function, and everything's fine and dandy.

Upvotes: 6

Dimas Cyriaco
Dimas Cyriaco

Reputation: 184

I didn't understand why you put:

where("params[:projectid] = ?", projectid)

if you receive params[:project] from the ajax request, the query string shouldn't be:

where("projectid = ?", params[:projectid])

intead?

And if you are receiving an empty string ('') as the parameter you can always test for:

unless params[:projectid].blank?

I don't think i undestood your question, but i hope this helps.

Upvotes: -1

Related Questions