Does not equal conditional
I want to have a where clause with an equal and does not equal condition:
@user = User.where(:user_id => current_user.id, :author_id != current_user.id).nil? ? (render :something) : (render :somethingelse)
The above does not work:
开发者_开发百科syntax error, unexpected ')', expecting tASSOC ...d, :user_id != current_user.id).nil? ? (render :index) : (re...
If I change the second condition from !=
to =>
it will work, however.
How do I have both conditions in one where clase? Thank you
Here's how you would use Arel to generate the query "select * from users where user_id = ? and author_id != ?
":
users = User.arel_table
User.where(users[:user_id]. eq(current_user.id).and(
users[:author_id].not_eq(current_user.id)))
Using Arel isn't as concise as using Hash conditions for simple conditions, but it's a lot more powerful!
Here's a link to the full list of predications (eq
, not_eq
, gt
, lt
, etc.) available with Arel.
I believe, it should be:
@user = User.where(['user_id = ? AND author_id <> ?', current_user.id, current_user.id])
render(@user ? :something : :somethingelse)
Rails 4 has this all figured out
Model.where.not(:colname => nil)
#=> returns all records whose :colname values are not nil
The syntax error is due to you attempting to use !=
instead of =>
. The where
method does not support inequality with hashed arguments, so your not equal will need to be written using array arguments.
User.where(:user_id => current_user.id).where(['users.author_id <> ?', current_user.id])
http://guides.rubyonrails.org/active_record_querying.html#hash-conditions
Only equality, range and subset checking are possible with Hash conditions.
You'll need to either drop down to straight SQL or invert and arel query, see Is there a way to invert an ActiveRecord::Relation query?
Not sure if you're aware, the not equal condition typically does not match (author_id) NULL values. You'll have to do an OR author_id IS NULL
if you want that.
@users = User.where("user_id = ? AND (author_id != ? OR author_id IS NULL)",
current_user.id, current_user.id)
render(@users.present? ? :something : :somethingelse)
Also note that I'm using @users.present?
because where
finder returns an ActiveRecord::Relation
array.
精彩评论