Jay
Jay

Reputation: 6244

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.

Upvotes: 0

Views: 180

Answers (2)

miguel.camba
miguel.camba

Reputation: 1827

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")

Upvotes: 1

Moiz Raja
Moiz Raja

Reputation: 5762

If using rails 3.x

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

Upvotes: 3

Related Questions