LoginSignup
0
0

More than 5 years have passed since last update.

Ransack ネストされたモデルの検索方法

Last updated at Posted at 2016-07-06

環境

ruby 2.1.0
Rails 4.1.0
ransack 1.7.0

RansackでShopモデルにネストされたItemsを検索したい

複数のItemsを持つShopモデルがあります。
gemRansackshop/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>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0