Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think you may have mistyped the query a bit. <code>"params[:projectid] = ?"</code> shouldn't be a valid query condition under any circumstances.</p> <p>In any case, you could do some sort of conditional statement:</p> <pre><code>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 </code></pre> <p>Although, I'd probably prefer something like this:</p> <pre><code>@conversations = current_user.conversations.limit(10) @converstaions.where("project_id = ?", params[:project_id]) unless params[:project_id].blank? </code></pre> <p>Sidenotes:</p> <ol> <li>You don't have to use <code>.find(:all)</code>. Rails will automatically execute the query when the resultset is required (such as when you do <code>@conversations.each</code>).</li> <li>Wherever possible, try to adhere to Rails' snakecasing naming scheme (eg. <code>project_id</code> as opposed to <code>projectid</code>). You'll save yourself and collaborators a lot of headaches in the long run.</li> </ol> <p>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</p> <p>EDIT: If you have multiple params that could be a part of the query, consider the fact that <code>where</code> takes a hash as its argument. With that, you can easily build a parameter hash dynamically, and pass it to <code>where</code>. Something like this, maybe:</p> <pre><code>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) </code></pre> <p>In the above case, you'd loop over all fields in the array, and add each one of them to the resulting hash <em>unless</em> it's blank. Then, you pass the hash to the where function, and everything's fine and dandy.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload