Rails模型结构,支持具有不同字段数的对象

时间:2016-06-01 14:58:40

标签: ruby-on-rails database-design

我想知道如何最好地构建一些Rails模型,以便它们可以支持不同数量的输入字段。

假设我有一个属于主题模型的文章模型。我想拥有任意数量的主题,我希望允许每个主题定义它自己的字段。例如,theme_1可能会定义primary_colour,而theme_2可能会定义colour_1,colour_2和font。

基本上,主题的选择决定了文章需要收集哪些额外信息才能正确应用主题。

如果article_1正在使用theme_1,那么每当我渲染article_1时,我都需要存储一个primary_color值。如果article_2也使用theme_1,我希望能够定义不同的primary_color值。同样,如果article_3使用theme_2,那么我需要存储color_1,color_2和font。

主题定义了必填字段,所需的值对于文章来说是唯一的。

到目前为止,我已经提出了以下内容,但我不相信它是最佳解决方案:

class Article < ActiveRecord::Base
  belongs_to :theme
  has_many :article_details
end

class Theme < ActiveRecord::Base
  has_many :fields
end

class ArticleDetail < ActiveRecord::Base
  belongs_to :field
  belongs_to :listing
end

文章有一个主题,一个主题有字段,所以我知道我需要填写文章的哪些字段。文章还有article_details,其中我存储了一个值和对该值所在字段的引用。

我希望我的说明清楚。任何反馈都表示赞赏。

由于

2 个答案:

答案 0 :(得分:0)

鉴于有多个潜在主题,并且您不打算根据所需字段进行查询更新,我建议使用散列列。所以像这样:

class Article < ActiveRecord::Base # Columns on the articles table include: # Indexed string called 'theme' # text column (not string!) called 'fields' serialize :fields
end

然后您将能够执行以下操作: a = Article.new a.fields = {color1: 'blue', color2: 'red', fontFamily: 'Verdana'} a.save

答案 1 :(得分:0)

我认为我过度思考这个解决方案。如果Article在Theme上有多态关联,那么我可以用我们自己的字段集定义n个主题:

class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.references :theme, polymorphic: true, index: true
    end
  end
end

class Article < ActiveRecord::Base
  belongs_to :theme, polymorphic: true
end

class MyTheme < ActiveRecord::Base
  has_one :article
end

此时如果MyTheme定义primary_color我可以这样做:

article = Article.new
article.theme = MyTheme.new(primary_color: 'blue')
article.save
article.theme.primary_color
 => 'blue'

暂时无论如何,满足我所寻找的目标。

相关问题