Product.rb
class Product < ActiveRecord::Base
has_many :categories, through: :product_categories
has_many :product_categories, dependent: :destroy
Category.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 =&gt; “发表”。我似乎无法弄清楚如何在控制器中接近这个?厌倦了,并且对SQL查询语法不太熟悉。请原谅我的无知:P
答案 0 :(得分:0)
的Gemfile
gem 'squeel'
category.rb
scope :with_published_products, -> { joins{product_categories.product}.where{products.status.eq "published"}.uniq }
static_pages_controller.rb
def catalog
@categories = Category.with_published_products
end
我的观点
- @categories.each do |category|
category.name
category.products.each do |product
= render 'product', :product => product
希望这有助于其他人...... :)