如果提供参数,则使用 Ransack 进行搜索

Search with Ransack if parameter is provided

我需要在学校控制器的显示视图上制作搜索表单,如果提供了参数,它将显示搜索结果,但我无法让它工作:

schools_controller

def show
    find_city
    find_school

    @search = @school.users.ransack(params[:q])

    if (params.has_key?(:q))
        @users = @search.result
    else
        @users = @school.users.all
    end
end

路线

  get "/cities/:city_id/school/:school_id" => "users#index", as: "users"
  get "/cities/:city_id/school/:school_id/user/new" => "users#new", as: "new_user"
  post "/cities/:city_id/school/:school_id" => "users#create"
  get "/cities/:city_id/school/:school_id/user/:id" => "users#show", as: "user"
  get "/cities/:city_id/school/:school_id/user/:id/edit" => "users#edit", as: "edit_user"
  patch "/cities/:city_id/school/:school_id/user/:id" => "users#update"
  delete "/cities/:city_id/school/:school_id/user/:id" => "users#destroy"

显示学校视图

<% title "#{@school.name}" %>

<div class="row">
    <div class="col-md-12 text-center city-title">
        <h3><%= @school.name %></h3>
    </div>
</div>

<%= search_form_for @search do |f| %>
    <%= f.label :full_name_cont %>
    <%= f.text_field :full_name_cont %>

    <%= f.submit %>
<% end %>

<div class="users">
    <% @users.in_groups_of(4, false).each do |users| %>

        <div class="row">

            <% users.each do |user| %>
                <div class="col-xs-6 col-md-3 text-center">
                    <a href="<%= user_path(@city, @school, user) %>" class="thumbnail school">
                        <%= image_tag user.avatar.url(:thumb), size: "100", class: "user-profile-image img-responsive" %>
                        <%= user.full_name %>
                    </a>
                </div>
            <% end %>

        </div>

    <% end %>

    <div class="row">
        <div class="col-md-12">
            <%= link_to city_path(@city), class: "btn btn-primary" do %>
                <span class="glyphicon glyphicon-chevron-left"></span> Back
            <% end %>

            <% if is_admin? %>
                <%= link_to new_user_path(@city, @school), class: "btn btn-primary" do %>
                    <span class="glyphicon glyphicon-plus"></span> Add user
                <% end %>
            <% end %>
        </div>
    </div>

</div>

我收到错误:

No route matches {:action=>"index", :city_id=>"1", :controller=>"users", :format=>nil, :id=>"3"} missing required keys: [:school_id]

我怎样才能做到这一点?

问题已解决;我只需要添加 URL 和 Ransack 对象:

<%= search_form_for @search, url: school_path(@city, @school) do |f| %>