【问题标题】:Using a variable string in find condition在查找条件中使用变量字符串
【发布时间】:2012-10-11 13:53:22
【问题描述】:

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

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

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

【问题讨论】:

  • 你得到什么错误?你用的是什么版本的 Rails?你正在尝试的应该工作,所以你的变量一定有问题。只是一个小注释:"#{the_style}"the_style 相同。像这样将变量放在引号中是没有用的。

标签: ruby-on-rails string conditional-statements


【解决方案1】:

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

Building.find(:last, :conditions => [" style = ?", the_style ]) 

【讨论】:

    【解决方案2】:

    无法准确说明导致错误的原因,但我会为这类事情创建一个命名范围

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

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

    Building.by_style(@house.style).last
    

    【讨论】:

      【解决方案3】:

      您将使用where 方法:

      Building.where(style: @house.style).first
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-27
        • 2011-04-13
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 2015-01-22
        相关资源
        最近更新 更多