In Ruby on rails 3 I want to query on a has_many field of a model as follows:
@project.items.where(:status => 1)
The problem is I'm trying to get the exact opposite result than this. What i want is all items of @projec开发者_运维问答t
where the status is not 1. Been looking for the answer to this for a while, anyone?
There are many ways to accomplish what you are trying to do, however, some are better than others. If you will always be searching for a hardcoded number (i.e. 1 in this case), then the following solution will work:
@project.items.where('status != 1')
However, if this value is not hard-coded, you are openly vulnerable to SQL injection as Rails will not (cannot) escape this kind of query. As a result, it is preferred among Rails developers to user the following syntax for most custom conditions (those that can't be constructed via Hash
):
@project.items.where(['status != ?', 1])
This syntax is slightly confusing, so let me go over it. Basically you are providing the where
clause an Array
of values. The first value in the array is a String
representing the query you want executed. Anywhere you want a value in that string, you place a ?
. This serves as a placeholder. Next, you add an element for every question mark in you query. For example, if I had the following:
where(['first_name = ? AND last_name = ?', params[:first_name], params[:last_name]]
Rails will automatically match these up forming the query for you. In that process, it also escapes potentially unsafe characters, preventing injection.
In general, it is preferred to use the Array syntax, even for a hardcoded value. I've been told that pure string conditions in Rails 3.5 will raise a warning (unverified), so it doesn't hurt to get in the process of using the Array syntax now.
精彩评论