2013-07-16 252 views
0

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 =>「published」。我似乎無法弄清楚如何解決這個問題,在控制器中?在SQL查詢語法上很累,並不是很熟悉。所以,請原諒我的無知:P

+0

@categories = Category.joins(:products).where('products.status'=>「published」) - 我在做什麼? _I使用這個複製類別名稱。 – Morphiuz

+0

檢查此帖是否可以幫助您解決問題 http://stackoverflow.com/questions/8031317/a-simple-rails-3-1-view-using-group -by 需要按類別分組並顯示其中的產品 – Icicle

+0

明白了,我會在完成後發佈我做的事情 – Morphiuz

回答

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 

希望這可以幫助別人... :)