我正在为我的ruby应用程序开发一个搜索表单。我现在想要使用3个text_fields,1个搜索按钮进行搜索。
我的代码看起来像这样
控制器
def search
params_name = params[:name].upcase.gsub("'", "\\\'").gsub("\"", "\\\"")
params_username = params[:username].upcase.gsub("'", "\\\'").gsub("\"", "\\\"")
params_email = params[:email].upcase.gsub("'", "\\\'").gsub("\"", "\\\"")
where_clauses = []
where_clauses << "UPPER(name) LIKE '%#{params_name}%'" if params_name.present?
where_clauses << "UPPER(username) LIKE '%#{params_username}%'" if params_username.present?
where_clauses << "UPPER(email) LIKE '%#{params_email}%'" if params_email.present?
# where_clauses << "UPPER(email) LIKE '%#{params_name}%' OR UPPER(first_name) LIKE '%#{params_name}%' OR UPPER(last_name) LIKE '%#{params_name}%' OR UPPER(username) LIKE '%#{params_name}%'" if params_name.present?
User.set_per_page(params[:per_page]) if params[:per_page].present?
base_user = User.where(where_clauses.join(" AND "))
@users_count = base_user.count
@users = base_user.paginate(:page => params[:page])
render :index
浏览
<div class="clearfix">
<div class="form-group pull-right">
<label class="right">Search</label>
<%= form_tag(search_users_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :name, params[:name], placeholder: "Search Users", class: "form-control" %>
<%= text_field_tag :username, params[:username], placeholder: "Search Users", class: "form-control" %>
<%= text_field_tag :email, params[:email], placeholder: "Search Users", class: "form-control" %>
<% end %>
</div>
</div>
我有错误。如何搜索=&gt;姓名,用户名和电子邮件?
由于
答案 0 :(得分:0)
你不应该试图逃避并自己消毒搜索参数。要以安全的方式编写LIKE
查询,请使用this answer中描述的技术。在您的示例中,它可能如下所示:
def search
User.set_per_page(params[:per_page]) if params[:per_page].present?
query = User.scope
[:name, :username, :email].each do |field|
if params[field].present?
query = query.where("UPPER(#{field}) LIKE :query",
query: "%#{params[field].upcase}%")
end
end
@users_count = query.count
@users = query.paginate(:page => params[:page])
render :index
end
此外,您可能希望将该实施提取到.search
上的User
方法。