2015-10-19 58 views
1

我可以撥打@product.categories,但不能撥打@product.categories.name@product.categories.parent_id,爲什麼?導軌類別型號問題

我在我的產品模型中使用Categorizable模塊。

class Product < ActiveRecord::Base 
include Categorizable 
end 

我有以下型號:

分類模型:

class Category < ActiveRecord::Base 
has_many :categoricals 
validates :name, uniqueness: { case_sensitive: false }, presence: true 
acts_as_tree order: "name" 


def find_subcategories 
    @subcategories = Category.where(:parent_id => params[:parent_id]) 
end 
end 

指標模型:

class Categorical < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :categorizable, polymorphic: true 

    validates_presence_of :category, :categorizable 
    end 

Categorizable模塊:

module Categorizable 
    extend ActiveSupport::Concern 

    included do 
    has_many :categoricals, as: :categorizable 
    has_many :categories, through: :categoricals 
    end 

    def add_to_category(category) 
    self.categoricals.create(category: category) 
    end 

    def remove_from_category(category) 
    self.categoricals.find_by(category: category).maybe.destroy 
    end 

    module ClassMethods 
    end 
end 

回答

3

因爲@product.categories返回一個集合,而不是一個實例。

@product.categories.first.name將工作(假設有類別)在他們

或環

<% @product.categories.each do |category| %> 
    <%= category.name %> 
<% end %>