-2

我有一个字符串变量如下:

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

将字符串变量放入查找条件的正确方法是什么?

4

3 回答 3

1

为什么要使用引号来逃避它们?

Building.find(:last, :conditions => [" style = ?", the_style ]) 
于 2012-10-21T16:46:32.550 回答
0

不能确切地说是什么导致了错误,但我会为这类事情创建一个命名范围

class Building < ActiveRecord::Base
  scope :by_style, lambda { |style| where("style = ?", style) }
  # ...
end

在你的控制器中,你可以做

Building.by_style(@house.style).last
于 2012-10-21T16:44:30.870 回答
0

您将使用以下where方法:

Building.where(style: @house.style).first
于 2012-10-21T16:47:06.850 回答