具有未知数量属性的模型

时间:2014-04-25 20:56:28

标签: ruby-on-rails ruby-on-rails-4

Ruby on Rails 4

我想创建一个模型"测试"可以有2到200个问题。会有很多测试。每个测试都会有不同的问题变化。

我正在考虑制作一个名为" questions_ids"的属性。我必须用逗号创建一个用question_id分隔的字符串。

或者我可以使用200个question_id属性制作模型。这将使question_id更容易和更快地检索。

还有其他方法吗?哪个更受欢迎?如果我有1000个问题该怎么办?谢谢

1 个答案:

答案 0 :(得分:1)

模型/ test.rb

class Test < ActiveRecord::Base
  has_many :test_questions
end

模型/ test_question.rb

class TestQuestion < ActiveRecord::Base
  belongs_to :question
  belongs_to :test
end

模型/ question.rb

class Question < ActiveRecord::Base
  has_many :tests
end

分贝/迁移/ initial_migration.rb

class InitialMigration < ActiveRecord::Migration
  def self.up

    create_table :tests do |t|
      t.string :name
    end

    create_table :test_questions do |t|
      t.references :table
      t.references :question
    end

    create_table :questions do |t|
      t.string :name
    end

  end

这也将创建适当的索引。

相关问题