简体   繁体   中英

Using .where with a comparison operators in Ruby

I'm trying to get user products whos quantity is not zero. I tried getting the products this way but it give me all products that belong to that user regardless of quantity.

@user = User.find(params[:id]) 
@products = @user.products.where(:quantity != 0)

Active Record uses a little magic here and there to help with conditions, but it is still Ruby, and there are limits to it. The expression

:quantity != 0

always evaluates to true . So your command ends up as:

@products = @user.products.where( true )

and that explains your unwanted result.

To code the query that you want, one possible syntax should be

@products = @user.products.where( "quantity != ?", 0 )

using a different way of constructing a SQL where clause. The placeholder syntax (using ? and a list of values) is not really necessary here, but you should use it instead of Ruby's variable interpolation (eg "#{variable}" ) as a matter of course, to reduce vulnerability to SQL injection attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM