Ruby on Rails 4 - 使用嵌套属性构建数据库

时间:2015-06-25 14:09:50

标签: ruby-on-rails

我在使用嵌套属性设置数据库时遇到了相当大的麻烦,即使经过数小时的谷歌搜索,我也找不到答案。我应该继续尝试解决这个问题,还是重新开始,因为我对如何构建数据库的想法有些不对?

我的结构是:

问题(将在向导中提出的问题,根据之前问题的答案呈现)

回复(问题的可能答案,user_input将保存用户对特定实验的响应(例如特定数字)的输入)

实验(向导正在组装的东西)

用户(有多个实验,每个实验都是向导的单独运行)

示例种子:

    Question.create(
 {
  :title => 'rm power analysis 2',
  :content => 'Look up what the next step should be. Maybe just display result of power analysis.', 
  :responses_attributes => [
    { content: 'Seperate measurements per subject:', input_type: 'number 2 20', next_question: 'rm power analysis 2'}, 
    { content: 'Seperate measurements per subject:', input_type: 'number 2 20', next_question: 'rm power analysis 2'},
    { content: 'unsure', input_type: 'radio', next_question: 'rm power analysis 2' }
  ], 
  :tell_me_more => 'lengthy explanation text goes here.'
 }
) 

class CreateQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|
      t.string :title
      t.text :content
      t.has_many :responses
      t.has_many :experiments, through: :responses
      t.timestamps
    end
  end
end

class AddTellMeMoreToQuestions < ActiveRecord::Migration
  def change
    add_column :questions, :tell_me_more, :text
  end
end

class Question < ActiveRecord::Base

  # ownerships
  has_many :responses, :dependent => :destroy
  accepts_nested_attributes_for :responses 
end

其他课程

class Experiment < ActiveRecord::Base
#ownerships
has_many :responses
accepts_nested_attributes_for :responses, :reject_if => lambda { |a|   a[:content].blank? }
has_many :questions, :through => :responses
belongs_to :user

  def current_question
    @current_question || questions.first
  end

end

class Response < ActiveRecord::Base

  # ownerships
  belongs_to :question
  belongs_to :experiment
end

class User < ActiveRecord::Base

  # Ownerships
  has_many :experiments, :dependent => :destroy
  accepts_nested_attributes_for :experiments, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
  has_many :responses, :through => :experiments
  accepts_nested_attributes_for :responses, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
  ...
end

attempt at UML structure

0 个答案:

没有答案