##環境
ruby 2.1.0
Rails 4.1.0
ransack 1.7.0
##Ransack ネストされた子モデルを親モデルごとのshowページで検索したい
複数のItem(子モデル)を持つShop(親モデル)があります。
gemRansack
でshop.show.html.erb
にItem一覧を表示し、店舗ごとのitem検索機能を作りたいと考えています。
一覧表示までは出来ていますが、検索とソートが機能しない状況です。
コンソールでは、親モデルだけ指定され全ての結果が返されていますので、検索・ソートが機能していない事までは分かりますが、改善の方法が分からずにおります。
ターミナル Started GET "/shops/1?utf8=%E2%9C%93&q%5Bname_cont%5D=%E5%90%8D%E5%89%8D&commit=%E6%A4%9C%E7%B4%A2" for 10.0.2.2 at 2016-07-15 11:51:37 +0000 Processing by ShopsController#show as HTML Parameters: {"utf8"=>"✓", "q"=>{"name_cont"=>"名前"}, "commit"=>"検索", "id"=>"1"} Shop Load (0.3ms) SELECT `shops`.* FROM `shops` WHERE `shops`.`id` = 1 LIMIT 1 Item Load (0.6ms) SELECT `items`.* FROM `items` WHERE `items`.`shop_id` = 1
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>
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。