我可以致电@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
答案 0 :(得分:3)
因为@product.categories
返回集合,而不是实例。
@product.categories.first.name
将起作用(假设有类别)
或循环播放
<% @product.categories.each do |category| %>
<%= category.name %>
<% end %>