Rails How to build model dynamically in controller?

kevinhua · 2011年11月06日 · 最后由 wxianfeng 回复于 2012年02月04日 · 2807 次阅读

For example:

Environment: Ruby 1.9.2 Rails 3.0.5 Mongoid

I have a Survey model and embeds many Questions in it. Now I want to define a function "publish" in 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```  

动态创建类

model = Class.new

class << model
  def foo
  end
end

#or

model.class_eval do
  def foo
  end
end

object = model.new
object.foo # => nil

不过不太理解你动态创建类的意图?

因为每个 Survey 包含的 Question 数量及顺序不同,所以要为不同的 Survey 准备一个 model 用于存放用户的答案。

@Rei,能否具体一些,另外,除了动态创建类外,如何根据@questions.each来动态地创建 attributes?

mongoid 本身支持动态属性

http://mongoid.org/docs/installation/configuration.html

allow_dynamic_fields

dynamic_fields:

anwser = Anwser.new
anwser['q1'] = 'some value'
anwser.save
anwser['q1'] # => 'some value'

直接当 Hash 用

感觉 @Kevin Hwa 问的问题应该是动态创建多条 questions,如果是这个问题,ActiveRecord 的 accepts_nested_attributes_for 配合 nested_form ( https://github.com/ryanb/nested_form ) 是完美的搭配。 而 mongoid 少用,我就不知道支持不支持 accepts_nested_attributes_for 之类的了。

@Kevin Hwa 看看这个视频 http://railscasts.com/episodes/196-nested-model-form-part-1 ,是不是你需要的功能

#7 楼 @Los 这个视频曾经看过。不过,我因为是在修改 ThunderSurvey,所以希望沿用他的格局。正好遇到这一个问题,所以想以最接近的方法解决。

#9 楼 @Kevin Hwa 就是说你需要实现的功能是不是视频中的那样?

基本上现在 Survey 和 Question 的 model 和 controllers 都已经完毕,关键就是需要根据 Survey 所含的 Question,动态创建用于存放答案的 model。

没理解需求,但是动态创建 Model 可以这样:

Object.const_set(:ModelName,Class.new(ActiveRecord::Base))

需要 登录 后方可回复, 如果你还没有账号请 注册新账号