简体   繁体   中英

In Rails, how do you get a variable that holds a database field name into a condition?

The following controller code doesn't work. Is there a way?

@m = "jan"
@teams = Team.find(:all, :conditions => ["@m = ?", true], :order => "name asc")

thanks.

如果使用Rails 3.x

@teams = Team.where(@m => true).order("name asc").all

You need to interpolate the string!

@m = "jan"
@teams = Team.find(:all, :conditions => ["#{@m} = ?", true], :order => "name asc")

And by the way, database queries when checking for booleans should use the IS operator

@m = "jan"
@teams = Team.find(:all, :conditions => ["#{@m} IS ?",true], :order => "name asc")

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