【问题标题】:how can I create a model that has different attributes depending on the type如何根据类型创建具有不同属性的模型
【发布时间】:2012-07-20 15:03:13
【问题描述】:

我有一个类别模型

   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
#

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

示例: 创建的类别:“书籍” 例如,他希望将字段“作者”存储在资源模型中。

创建的类别:“会议” 例如,他希望将字段“位置”、“日期”存储在资源模型中。

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

【问题讨论】:

    标签: ruby-on-rails associations models


    【解决方案1】:

    一个想法是为一个类别的字段创建一个单独的表。例如,您的设置可能如下所示:

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

    然后,当您的客户创建一个新类别时,即Books,他可以向该类别添加一个名为author 的新类别字段。然后,如果他想将新作者添加到 Books 类别,他会将 category_field_value(即 JK Rowling)添加到 author category_field

    因此, Books category 会有一个author category_fieldauthor category_field 会有一个category_field_value (JK Rowling)。

    【讨论】:

    • 谢谢迈克尔,我会看看的。我很欣赏你的想法。
    【解决方案2】:

    你可以去看看>>https://github.com/moiristo/dynamic_attributes

    或者您考虑使用 MongoDB 或 redis 等无模式数据库?

    你也可以使用hstore,它是postgresql中的键值类型。

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 1970-01-01
      • 2022-01-10
      • 2021-09-28
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多