Rails 4 - 通过索引操作表单中的collection_select值过滤索引

时间:2013-10-05 16:27:09

标签: ruby-on-rails forms scope ruby-on-rails-4 filtering

Record:
  belongs_to :user
  has_one :course
  has_one :client, through: :user
  has_one :group, through: :user

在Record的索引操作页面上我想为客户端,组和用户创建一个带有collection_selects的表单(表单,我已经制作了相关的collection_selects)...但我不知道如何制作表单提交按钮返回过滤的索引页。

我有范围设置只是不知道如何从表单中调用它们。

记录模型w /范围:GitHub Link

_index_filter_form部分视图:GitHub Link

记录控制器:GitHub Link

1 个答案:

答案 0 :(得分:0)

最初我在视图中看到了这个:

<td><%= collection_select(:client_id, 0, Client.find(:all, :order => "name"), :id, :name, {}, {:class=>'form-control'}) %></td>
<td><%= collection_select(:group_id, 0, Group.find(:all, :order => "name"), :id, :name, {}, {:class=>'form-control'}) %></td>
<td><%= collection_select(:user_id, 0, User.find(:all, :order => "first_name, last_name"), :id, :full_name, {}, {:class=>'form-control'}) %></td>

我回过头来看看我是如何传递参数的......并修改了上面的代码:

<!-- collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) -->
<td><%= collection_select(:client, :id, Client.find(:all, :order => "name"), :id, :name, {}, {:class=>'form-control'}) %></td>
<td><%= collection_select(:group, :id, Group.find(:all, :order => "name"), :id, :name, {}, {:class=>'form-control'}) %></td>
<td><%= collection_select(:user, :id, User.find(:all, :order => "first_name, last_name"), :id, :full_name, {:multiple => true, :size => 5}, {:class=>'form-control'}) %></td>

现在,我可以在表单提交后通过控制器上的索引操作访问params。

def index
    @records = Record.all
    if params[:commit] == "Filter"
      @records.by_client(params[:client_id]).by_group(params[:group_id]).by_user(params[:user_id])
    end
end

其中by_client,by_group和by_user是位于记录模型中的命名范围。