有没有办法根据其他模型的记录建立模型?

时间:2011-11-07 15:35:19

标签: ruby-on-rails object mongoid models

例如:

环境:

Ruby 1.9.2

Rails 3.0.5

Mongoid

我有一个Survey模型,并在其中嵌入了许多问题。现在我想在surveys_controller.rb中定义一个函数“publish”,它可以根据Survey的记录(即对象)动态创建模型:

#surveys_controller.rb
def publish
  @survey = Survey.find(params[:id])
  @questions = Survey.questions
  ... how to build a model? ...
  @questions.each do |question|
    ... and then how to add fields (named with question.title) and define type (named with question.type) ...
  end
end

1 个答案:

答案 0 :(得分:0)

我假设您的模型看起来像这样:

class Survey < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
end

您可以通过以下方式创建与调查相关的问题:

def publish
  # here, we instantiate an object by loading
  # a record from the Survey model
  @survey = Survey.find( params[:id] )
  # here, we instantiate an object of class Question,
  # associated to our object from class Survey.
  # the argument passed to the build() method 
  # depends on your form.
  @question = @survey.questions.build( params[:question] )
  # when we save our @survey, its associated @question
  # will be saved as well
  @survey.save
end

您可能希望将validates_associated :questions添加到Survey模型中,以确保您的问题在保存时有效。 有关详情,请参阅Ruby on rails guidesRails API doc