如何在铁轨上的类别下展示产品

时间:2016-07-21 11:44:12

标签: ruby-on-rails ruby ruby-on-rails-5

正在使用rails应用程序并在显示页面上查找某个类别,我想显示在该类别下找到的所有产品  这是我的方式

在类别中显示是

def show
    @products = Category.friendly.where(params[:name])
  end

在我的观点中,我有这样的

<% @products.each do |product| %>

<%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %>
<div class="product-image">
<%= image_tag product.productpic.url if product.productpic? %>
</div>

  <div class="product-text">
    <h2 class="product-title"> <%= product.name %></h2>
      <h3 class="product-price">£<%= product.price %></h3>
  </div>

    <% end %>
<% end %>

这是我的产品型号

class Product < ApplicationRecord
  belongs_to :category
  mount_uploader :productpic, ProductpicUploader
   has_many :order_items
acts_as_taggable
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
 default_scope { where(active: true) }
end

和我这样的类别

class Category < ApplicationRecord
  has_many :products
  extend FriendlyId
 friendly_id :name, use: [:slugged, :finders]
end

我在这里做错了什么?

3 个答案:

答案 0 :(得分:1)

你的发现者得到的分类 ies ,而不是产品:

def show
  @categories = Category.friendly.where(params[:name])
end

如果您有适当的关系,则可以迭代给定类别中的每个产品。由于方法where返回关系,因此首先需要迭代它。

<% @categories.each do |category| %>
  <% category.each do |product| %>
    <div class="product-category">
      Category:
      <%= product.category.name %>
    </div>
    <div class="product-text">
      <h2 class="product-title"> <%= product.name %></h2>
      <h3 class="product-price">£<%= product.price %></h3>
    </div>
  <% end %>
<% end %>

答案 1 :(得分:0)

您正在执行错误的查询。您正在使用category,但您必须使用您需要的相关products

应该是这样的, @products = Category.friendly.where(name: params[:name]).first.products

然后在视图代码中,您可以迭代一个类别的产品。

答案 2 :(得分:0)

试试这个,

def show
  category = Category.friendly.find_by_name(params[:name])
  @products = category.products
end