Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在查找条件中使用变量字符串_Ruby On Rails_String_Conditional Statements - Fatal编程技术网

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
相同。把你的变量放在那样的引号里是没有用的。