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

时间:2016-10-28 18:08:13

标签: ruby-on-rails ransack

我需要在学校控制器的展示视图上创建搜索表单,如果提供了参数,我会无法显示搜索结果:

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]

我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

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

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