假设我有两个模型:客户和产品
Client的“username”和“email”应该是“unique index”,作为Product的“serialnumber”
当用户在作为唯一索引的表单字段上键入内容时,我有一个 onblur 函数,它使用属性名称和属性值向 Controller 发送请求。如果值存在,将立即通知用户。
在 ClientController 中,我编写了一个函数来检查它是否唯一,并在错误时返回 -2,在不存在时返回 -1,如果存在则返回正数(id)。
def unique
if params[:attrName].blank? or params[:attrValue].blank?
id = "-2"
else
cli = Client.where("#{params[:attrName]} = '#{params[:attrValue]}'").first
if cli != nil
id = cli["id"]
else
id = "-1"
end
end
render :json => {
:id => id
}
end
由于很多原因(SQL 注入(inject)漏洞、违反 DRY,因为每个 Controller 都具有基本相同的方法),这并不好。
我正在考虑在 ApplicationController 中编写“唯一”函数,但正如您在上面看到的,如果它是客户端,我应该能够调用“Client.where”,如果它是产品,我应该能够调用“Product.where”。我怎样才能以最“通用”的方式和最安全的方式构建这个功能?我正在考虑原始 SQL,但我认为这是一种幼稚的方法。
最佳答案
为此避免使用原始 SQL 是明智的。
这行得通吗?
class ApplicationController < ActionController::Base
def unique
id = if params[:attrName].blank? || params[:attrValue].blank?
-2
elsif found = model_name.where(params[:attrName] => params[:attrValue]).take
found.id
else
-1
end
render json: { id: id }
end
end
您可以将它放在 application_controller.rb
中,然后在您的 ClientsController
和 ProductsController
中定义 model_name
方法:
class ClientsController < ApplicationController
def model_name
Client
end
end
class ProductsController < ApplicationController
def model_name
Product
end
end
这会起作用,但可能并不理想。您可能希望使用 find
让 Rails 完成更多工作提高模型是否存在和strong params用于验证您需要的参数是否存在。
关于ruby-on-rails - 如何从 ApplicationController 调用模型的 where(...) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216750/