我的autocomplet工作,它看起来不错,但是哦,男孩,控制器是一团糟。自动完成功能会搜索多个模型,这些模型对事情没有帮助,并总计了找到的集合等等 - 有客户的国家标志等。
我想将其提取到理想的部分或其他方式,以使代码更容易处理。
def autocomplete
customer_count = (Customer.select("company").where("LOWER(company) LIKE ? AND deleted != ?", "#{params[:term].downcase}%", true).count) + (Product.select("model_number,description").where("LOWER(description) LIKE ? OR LOWER(model_number) LIKE ? AND deleted != ?", "#{params[:term].downcase}%", "#{params[:term].downcase}%", true).count) + (Order.where("LOWER(order_number) LIKE ? AND deleted != true","#{params[:term].downcase}%").count)
@customers = [{:label => (customer_count > 1 ? "<div style='font-weight: bold; text-align: left;'>Show all #{customer_count} records</div" : customer_count > 0 ? '' : "<div style='font-weight: bold; text-align: left;'>No records found</div>"), :link => "/customers?company=#{params[:term].downcase}"}]
@customers.concat(Customer.select("id, company, country").where("LOWER(company) LIKE ? AND deleted != ?", "#{params[:term].downcase}%", true).limit(24).collect{|customer|{:label=>("<div style='float:left;margin-top:4px;margin-right:8px;'><img alt='Mini_usa' src='/images/#{customer.country_div}'/></div> #{customer.company}").html_safe,:link =>"/customers/#{customer.id}"}})
@customers.concat(Product.select("id, model_number, description").where("LOWER(description) LIKE ? OR LOWER(model_number) LIKE ? AND deleted != ?","#{params[:term].downcase}%","#{params[:term].downcase}%",true).limit(24).collect{|product|{:label => ("#{product.model_number.titlecase} #{product.description.titlecase}").html_safe,:link =>"/products/#{product.model_number}"}})
@customers.concat(Order.select("id, order_number").where("LOWER(order_number) LIKE ? AND deleted != true","#{params[:term].downcase}%").limit(24).collect{ |order| { :label => ("#{order.order_number}").html_safe, :link =>"/orders/#{order.id}" } })
end
答案 0 :(得分:2)
为什么不为每个模型制作autocomplete
(或者search
是一个更好的上下文名称)方法,然后从控制器中调用和组合它们?这使得负责知道如何搜索数据本身所在的位置(在模型中)。
一般来说,您希望在模型中使用逻辑,而不是控制器。