Rails 类别模型问题
Rails categories model issue
我可以调用@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
可分类模块:
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
因为@product.categories
returns一个集合,而不是一个实例。
@product.categories.first.name
会起作用(假设有类别)
或遍历它们
<% @product.categories.each do |category| %>
<%= category.name %>
<% end %>
我可以调用@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
可分类模块:
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
因为@product.categories
returns一个集合,而不是一个实例。
@product.categories.first.name
会起作用(假设有类别)
或遍历它们
<% @product.categories.each do |category| %>
<%= category.name %>
<% end %>