如何列出与某个类别相关的所有项目

问题描述:

当从导航面板中单击相关类别名称时,我想显示与某个类别相关的所有项目。 这是我的导航面板如何列出与某个类别相关的所有项目

<ul class="nav navbar-nav"> 
     <li class="active"><a href="#">Home</a></li> 
     <li><%=link_to "About us" ,pages_about_path %></li> 
    <li><%=link_to "Contact us" ,pages_contact_path %></li> 
     <% @categories.each do |category| %> 
       <li><%=link_to category.name,category %><br></li> 
     <%end%> 
    </ul> 

这是类别

<div class="container"> 
<div class="col-md-12"> 
    <h1><%= @category.name %></h1> 
     <div> 
      <% @items.each do |item| %> 
        <div class="col-sm-4"> 
         <div class="panel panel-primary"> 
          <div class="panel-heading"> 
            <%= link_to item.title,item,class:"btn btn-primary btn-block" %> 
          </div> 
          <div class="panel-body"> 
           Quantity :<%= item.qty %><br> 
           Price : <%= number_to_currency(item.price, unit: "RS ") %><br> 
          </div> 
          <div class="panel-footer"> 
           <%= link_to "Edit" ,edit_item_path(item) , class: "btn btn-default" %> 
           <%= link_to "Delete" ,item , :confirm => "Are you sure?" , :method => :delete , class: "btn btn-danger"%> 
          <hr> 
          </div> 
         </div> 
        </div> 
       <%end%> 

用于我的节目视图的代码这是在类别控制器方法。

def show 
    @category =Category.find(params[:id]) 
    @items = Item.all 
end 

当我使用这些块时,所有的项目正在显示。

这是数据库中的表是如何

class CreateItems < ActiveRecord::Migration[5.0] 
    def change 
    create_table :items do |t| 
     t.string :title 
     t.float :qty 
     t.decimal :price 
     t.integer :category_id 

     t.timestamps 
    end 
    end 
end 


class CreateCategories < ActiveRecord::Migration[5.0] 
    def change 
    create_table :categories do |t| 
     t.string :name 

     t.timestamps 
    end 
    end 
end 

@items = Item.all回报,不论类别的所有项目。您需要将其更改为@items = @category.items

def show 
    @category = Category.find(params[:id]) 
    @items = @category.items 
end 

分类器显示应更改如下:

def show 
    @category = Category.find(params[:id]) 
    @items = @category.items #Item.all returns all items irrespective of a category 
end 

在此之前,确保有一个的has_many和belongs_to的类别模型和项目模型定义的关联,

在分类模型(category.rb)

has_many :items 

在项目模型(item.rb)中,

belongs_to :category