我想列出一个表,其中包含从数据库到表的过滤参数。我为它们分配了默认参数,但是我收到错误:参数数量错误(0表示4)
在我的模特中:
class Company < ActiveRecord::Base
scope :filtered, lambda {|count_min, count_max, city, company_status| where(:company_status => company_status, :ap_veh_count => count_min..count_max, :office_adress_city => city, )}
在控制器中:
class LeadsController < ApplicationController
before_filter :confirm_logged_in
def list
params[:sort] ||= "name"
params[:direction] ||= "asc"
params[:company_status] ||= "3"
params[:count_min] ||= "8"
params[:count_max] ||= "20"
params[:city] ||= "Rīga"
@companies = Company.filtered.order(params[:sort] + " " + params[:direction])
end
在视图中:
<% @companies.each_with_index do |company, i| %>
<tr>
<td><%= i + 1 %></td>
<td><%= company.ap_veh_count %></td>
<td><%= link_to company.name, {:action => 'view', :id => company.id} %></td>
<td><%= company.office_adress_city %></td>
<td><%= company.phone %></td>
<td><%= company.company_field %></td>
<td><%= company.email %></td>
<td><%= 'taisīt' %></td>
<td><%= link_to "Atlasīt", {}, :class => 'btn btn-success btn-mini' %></td>
</tr>
<% end %>
答案 0 :(得分:3)
嗯,您必须将参数传递给
上的过滤方法@companies = Company.filtered(params[:count_min], params[:count_max], etc.).order...
您可能希望将范围定义为:
scope :filtered, lambda { |*args|
count_min = args.shift || 8
count_max = args.shift || 20
city = args.shift || "Rīga"
company_status = args.shift || 3
where(
:count_min = count_min,
:count_max = count_max,
:city = city,
:company_status => company_status
)
}
为了拥有您的值的默认值。但你仍然必须传递参数(即使它们返回nil),以便万一它们是一个集合,它们将覆盖默认值。
答案 1 :(得分:2)
@companies = Company.filtered( !!! )
你应该通过count_min, count_max, city, company_status