【问题标题】:Is there a way to build model according to other model's records?有没有办法根据其他模型的记录来构建模型?
【发布时间】:2011-11-07 15:35:18
【问题描述】:

例如:

环境:

Ruby 1.9.2

Rails 3.0.5

Mongoid

我有一个调查模型并在其中嵌入了许多问题。现在我想在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

【问题讨论】:

  • 我不确定你到底在问什么。您是要实例化现有模型(例如 Question 模型)还是真正创建一个全新的模型对象(称为什么?),它将在数据库中创建一个全新的表......在运行中?顺便说一句,我建议不要这样做……也许如果你解释一下为什么你认为你需要这样做,我们可以重新设计你的设计并做一些可以在现有代码库中更多工作的事情。
  • @Taryn 是对的,您表达它的方式似乎将对象与类混淆,将模型与来自该模型的记录混淆。我认为您想要的是创建一个与您的 Survey 记录相关联的 Question 记录,所以我将回答如何做到这一点 - 但如果您真的将对象与类混淆,您应该真正了解更多关于 OOP ,这真的很重要。

标签: ruby-on-rails object mongoid models


【解决方案1】:

我假设您的模型如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2020-10-18
    • 2020-03-21
    • 1970-01-01
    • 2021-02-27
    • 2019-08-30
    相关资源
    最近更新 更多