2015-09-03 18 views
1

我在,如果一个字段的值在database.In已经存在我来说,我已经检查了多个领域,如用户名,检查控制器的方法,电子邮件和通过AJAX的URL。使用字符串变量作为字段名,其中条件轨4

所以我写了以下功能

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 

,并调用这个方法

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 

但在执行它抛出错误

Mysql2 ::错误:未知列“merchant_urls 'Where'条款':SELECT merchant_urls。* FROM merchant_urls其中merchant_urlsfield =“http://localhost:3000

那么,有没有任何使用字符串变量作为字段名的方法? 谢谢。

回答

3

它看起来像我这样做是错误的方式。当你逝去的标识加入方法(PARAMS内),为什么不能用它来获得merchant_url,然后检查该字段有内容:

def check_field_already_exist?(field, id=nil) 
    if id && merchant_url = MerchantUrl.find(id) 
    merchant_url.send(field).try('present?') 
    else 
    MerchantUrl.exists?(field => filter_params[field.to_sym]) 
    end 
end 

然后,您可以

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

虽然个人,我会有一个方法将模型实例属性hash作为json返回,然后使用JavaScript客户端检查散列的内容。这样,只需要一次回调服务器(而不是每个字段一次)就可以获得所需的数据。

+0

谢谢ReggieB我没有PARAMS:在所有情况下[ID]。 我在新的和编辑的情况下都使用同样的方法。所以如果我验证新的表单,它不会传递id,但是在编辑表单的情况下,它会这样做。 –

+0

@bipashant我修改了我的答案,以便它在没有id的情况下工作(在这种情况下,它将返回nil)。 – ReggieB

+0

@bipashant我再次修改了我的答案,以便它将检查其他商家网址中的这些字段(如果没有现有字段)。 – ReggieB

1

在产油虽代码field是标识列名的符号。 你应该这样做:

merchant_url = MerchantUrl.where("#{field} = ?", filter_params[field.to_sym]) 
0

我希望这个作品

def check_field_already_exist?(field, params) 

    merchant_url = MerchantUrl.where("#{field}=?", filter_params[field.to_sym]).first 

    is_available = if (params[:id] && merchant_url) 
        merchant_url.id == params[:id] 
        else 
        merchant_url.nil? 
        end 
    end 

但要确保field不应该的东西,最终用户可以通过设置PARAMS ..其他明智的,这将是极其脆弱。

+0

大谢谢它的工作原理! –

+0

我很惊讶,这工作作为'where'将返回一个merchant_url实例的集合。所以下面的'merchant_url.id'将会出错或者返回集合的id。你可以使用'find_by'而不是'where',但是会找到第一个,并且可能会错过你之后的那个。你可以试试'mechant_url.collect(&:id).include?(params [:id])'或使用我的替代方案。 – ReggieB

+0

我认为这会更好,如果你相应地编辑你的答案@ReggieB – illusionist

4

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

merchant_url = MerchantUrl.where(field => filter_params[field])