产品.rb
class Product < ActiveRecord::Base
has_many :categories, through: :product_categories
has_many :product_categories, dependent: :destroy
类别.rb
class Category < ActiveRecord::Base
attr_accessible :name
# accepts_nested_attributes_for :product_categories
has_many :products, through: :product_categories
has_many :product_categories, dependent: :destroy
default_scope :order => 'id'
end
static_pages_controller.rb
...
def catalog
@categories = Category.all
render layout: "catalog"
end
我的观点:
// uses tabbable navigation from bootstrap to iterate over the categories, then it iterates over each product and inserts them into .tab-content
.row-fluid
.span8.offset2
.tabbable
%ul.nav.nav-tabs
%li.active
%a{"data-toggle" => "tab", :href => "#tab-#{@categories.first.id}"} #{@categories.first.name}
- @categories.each do |category|
-unless category == @categories.first
%li
%a{"data-toggle" => "tab", :href => "#tab-#{category.id}"} #{category.name}
.tab-content
.tab-pane.fade.in.active{id: "tab-#{@categories.first.id}"}
%h3.center #{@categories.first.name}
%hr
- if @categories.first.products.count == 0
.span6.offset3
This category is empty.
-else
- @categories.first.products.each do |product|
= render 'product', :product => product
- @categories.each do |category|
-unless category == @categories.first
.tab-pane.fade{id: "tab-#{category.id}"}
%h3.center #{category.name}
%hr
- if category.products.count == 0
.span6.offset3
This category is empty.
-else
- category.products.each do |product|
= render 'product', :product => product
目前它显示了一个类别中的每个产品。我希望它只显示:status =>“已发布”的产品。我似乎无法弄清楚如何在控制器中解决这个问题?累了,对 SQL 查询语法不是很熟悉。所以请原谅我的无知:P