2012-07-20 39 views
0

我有一个分类模型我怎样才能创建具有取决于类型

default_scope :order => 'display_order asc' 
    has_many :resources, :dependent => :destroy 

# == Schema Information 
# 
# Table name: categories 
# 
# id   :integer(4)  not null, primary key 
# name  :string(255) 
# description :string(255) 
# created_at :datetime  not null 
# updated_at :datetime  not null 
# 

我有一个资源模型不同属性的模型:

belongs_to :category 
    # belongs_to :submitter, :class_name => 'User', :foreign_key => "submitter_id" 
    has_and_belongs_to_many :filetypes 
    has_many :users, :through => :kits 
    has_many :kits 
    belongs_to :submitter, class_name: "User" 
    belongs_to :author 

==架构信息

# 
# Table name: resources 
# 
# id     :integer   not null, primary key 
# title    :string(255) 
# url    :string(255) 
# description  :string(255) 
# price    :decimal(,) 
# created_at   :datetime  not null 
# updated_at   :datetime  not null 
# category_id  :integer 
# image_file_name :string(255) 
# image_content_type :string(255) 
# image_file_size :integer 
# image_updated_at :datetime 
# status    :string(255) 
# submitter_id  :integer 
# author_id   :integer 
# 

客户希望能够创建类别,但根据类别为资源分配不同的属性。

例如: 创建类别:'Books' 他希望将字段“作者”存储在资源模型中。

创建的类别:'Conference' 他希望将字段'location','date'存储在资源模型中。

我该如何对其进行建模,使其动态且易于长期维护?

回答

0

一个想法是为一个类别的字段设置一个单独的表。例如,你可以设置这个样子:

category HABTM category_fields 
category_field HABTM categories 
category_field has_many category_field_values 
category_field_value belongs_to category_field 

然后,当你的客户创造了一个新的类别,即Books,他可以一个新category_field添加到类别称为author。然后,如果他想向Books类别添加新作者,他会将一个category_field_value(即JK Rowling)添加到authorcategory_field

因此, 的Books category将具有author category_field,并且author category_field将有一个category_field_value(罗琳)。

+0

谢谢迈克尔我会看看。我很欣赏你的想法。 – chell 2012-07-24 00:13:33