我在,如果一个字段的值在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_urls
。 field
=“http://localhost:3000”
那么,有没有任何使用字符串变量作为字段名的方法? 谢谢。
谢谢ReggieB我没有PARAMS:在所有情况下[ID]。 我在新的和编辑的情况下都使用同样的方法。所以如果我验证新的表单,它不会传递id,但是在编辑表单的情况下,它会这样做。 –
@bipashant我修改了我的答案,以便它在没有id的情况下工作(在这种情况下,它将返回nil)。 – ReggieB
@bipashant我再次修改了我的答案,以便它将检查其他商家网址中的这些字段(如果没有现有字段)。 – ReggieB