環境
ruby 2.1.0
Rails 4.1.0
ransack 1.7.0
RansackでShopモデルにネストされたItemsを検索したい
複数のItemsを持つShopモデルがあります。
gemRansack
でshop/show.html.erb
にitems一覧を表示し、店舗ごとのitem検索機能を作りたいと考えています。
一覧表示までは出来ていますが、検索機能とソート機能が機能しない状況です。
どこにミスがあるのか教えて頂けませんでしょうか。。
routes.rb
Rails.application.routes.draw do
resources :shops do
resources :items
end
end
models/shop.rb
class Shop < ActiveRecord::Base
belongs_to :user
has_many :items , dependent: :destroy
shops_controller.rb
def show
@shop = Shop.find(params[:id])
@q = @shop.items.ransack(params[:q])
@q.sorts = 'price asc' if @q.sorts.empty?
@shop.items = @q.result(distinct: true)
respond_with(@shop.items)
end
shop/show.html.erb
<h1>店舗詳細</h1>
<p>
<strong>Image:</strong>
<% if @shop.image? %>
<td><%= image_tag @shop.image_url(:thumb).to_s , :width => '300'%></td>
<% end %>
</p>
<p>
<strong>Name:</strong>
<%= @shop.name %>
</p>
<p>
<strong>City:</strong>
<%= @shop.city %>
<h1>商品一覧</h1>
<%= search_form_for @q, url: items_path(params[:shop_id]) do |f| %>
<%= f.label :name_or_content_cont, "商品名or説明文" %>
<%= f.search_field :name_or_content_cont %>
<%= f.submit '検索'%>
<% end %>
<table>
<thead>
<tr>
<th>ShopName</th>
<th>ItemImage</th>
<th>ItemName</th>
<th><%= sort_link(@q,:item_price,'値段') %></th>
<th>Content</th>
<th colspan="3"></th>
</tr>
</thead>
<%= render @shop.items %>
</table>