-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

where次の方法を使用します。

Building.where(style: @house.style).first
于 2012-10-21T16:47:06.850 に答える
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 に答える