在 rails 4 中的 where 条件中使用字符串变量作为字段名称

Bib*_*rma 2 ruby-on-rails ruby-on-rails-4

我在控制器中有一个方法,它检查一个字段的值是否已经存在于数据库中。在我的例子中,我必须通过 AJAX 检查多个字段,例如用户名、电子邮件和 URL。

所以我写了下面的函数

  def check_field_already_exist?(field, params )

    merchant_url = MerchantUrl.where(field: filter_params[field.to_sym]).first

     # here params[:id] is available only while editing the MerchantUrl
     is_available = if (params[:id] && merchant_url)
                 merchant_url.id == params[:id]
               else
                 merchant_url.blank?
               end
  end
Run Code Online (Sandbox Code Playgroud)

并调用此方法作为

  def is_name_available
    render json: check_field_already_exist?('username', params)
  end

  def is_url_available
    render json: check_field_already_exist?('url', params)
  end

  def is_email_available
    render json: check_field_already_exist?('email', params)
  end
Run Code Online (Sandbox Code Playgroud)

但在执行时它会抛出错误

Mysql2::Error: 'where 子句'中的未知列 'merchant_urls.field ': SELECT merchant_urls.* FROM merchant_urlsWHERE merchant_urlsfield= ' http://localhost:3000 '

那么,有没有什么方法可以使用字符串变量作为字段名?谢谢你。

Ser*_*sev 5

正确的方法是使用好老hashrocket语法

merchant_url = MerchantUrl.where(field => filter_params[field])
Run Code Online (Sandbox Code Playgroud)