Ruby on rails 在查找条件中使用变量字符串
我有一个字符串变量,如下所示:Ruby on rails 在查找条件中使用变量字符串,ruby-on-rails,string,conditional-statements,Ruby On Rails,String,Conditional Statements,我有一个字符串变量,如下所示: the_style = @house.style # this is a string variable and contains the value "modern" Building.find(:last, :conditions => [" style = ?", "#{the_style}" ]) 如果我在数据库中搜索如下: the_style = @house.style # this is a string variable and
the_style = @house.style # this is a string variable and contains the value "modern"
Building.find(:last, :conditions => [" style = ?", "#{the_style}" ])
如果我在数据库中搜索如下:
the_style = @house.style # this is a string variable and contains the value "modern"
Building.find(:last, :conditions => [" style = ?", "#{the_style}" ])
我在上面得到一个错误,但是如果我在字符串值中硬编码,它会工作:
Building.find(:last, :conditions => [" style = ?", "modern" ])
将字符串变量放入查找条件的正确方法是什么?不能确切地说是什么导致了错误,但我会为这类事情创建一个命名范围
class Building < ActiveRecord::Base
scope :by_style, lambda { |style| where("style = ?", style) }
# ...
end
为什么使用引号只是为了逃避它们
Building.find(:last, :conditions => [" style = ?", the_style ])
您可以使用
where
方法:
Building.where(style: @house.style).first
你有什么错误?您使用的是什么版本的Rails?您正在尝试的应该是有效的,所以您的变量一定有问题。只有一个小提示:
“{the_style}”
与the_style
相同。把你的变量放在那样的引号里是没有用的。