如何通过Rails中的params和用户输入进行过滤

时间:2018-06-05 20:08:14

标签: ruby-on-rails

我试图只显示属于我的应用程序中某些状态的行。我可以在Javascript中做很多事情,但我更愿意更好地理解控制器中的Rails和查询。我想将用户带到另一个页面,然后只显示该州的公司。没有必要将它们链接到另一个页面会很棒。有谁知道怎么做?

以下是我在控制器中的内容

  def vendors
    @vendors = Collective.where(sort: 'Vendor').all
    @vendors = @vendors.where(params[:state])
  end

我的路线

get '/vendors/:state', to: 'collectives#vendors'

然后我使用定型方法在html.erb文件中打印一个表。

<% @vendors.each do |company| %>

<tr>
  <td><%= company.name %></td>
  <td><%= company.state %></td>
 etc...

2 个答案:

答案 0 :(得分:2)

您的控制器代码是否应更改以下内容:

def vendors
  @vendors = Collective.where(sort: 'Vendor').all
  @vendors = @vendors.where(state: params[:state])
end

或更好:

def vendors
  @vendors = Collective.where(sort: 'Vendor', state: params[:state])
end

答案 1 :(得分:1)

使用会话代替网址参数。

这或多或少是你可以做的,对不起,如果它不是完全适用于你的情况,只是为了提出一个想法。

# view collectives/index (or whatever you have)

<%= form_tag (controller: :collectives, action: :set_status_filter, method: :post) do %>
  <%= select_tag(:session_status_filter, options_for_select(@your_list_of_options_for_the_filter)) %>
  <%= submit_tag "Set filter" %>
<% end %>


# collectives controller

def index # or whatever, this is the page containing the form and the list to show
  @vendors = Collective.where(sort: 'Vendor').all
  if session[:session_status_filter] == # etcetera
    then @vendors = @vendors.where(state: session[:session_status_filter]) # for example
  else # another option just in case, etcetera
  end
end

def set_status_filter # this action is called by the form
  session[:session_status_filter] = params[:session_status_filter]
    respond_to do |format|
      format.html { redirect_to *** the view where the form is placed ***, notice: 'the filter is set to: ....' + session[:session_status_filter] } # after the session variable is set the redirects goes to index which uses the session to filter records
    end
end

params[:session_status_filter]由表单传递给collectives#set_status_filter。该值用于设置会话变量。之后,操作collectives#set_status_filter会重定向到索引,或者您放置表单和要显示的列表的任何页面。