【问题标题】:How to create object within creation of another object?如何在创建另一个对象时创建对象?
【发布时间】:2015-08-12 18:45:13
【问题描述】:
我在 rails 和 mongoid 上使用 ruby。我有一个名为 Project 的模型和一个名为 Person 的模型。我想在初始化新项目时自动创建一个新的 Person 对象。有什么方法可以插入代码以在 Project 模型中创建一个新的 Person 。例如,当我执行“Project.create(:name => 'Project 1')”时,我希望它自动创建一个新的 Person 对象。我已经声明了模型之间的一对一关系。
需要重写Project模型的create方法吗?
【问题讨论】:
标签:
ruby-on-rails
ruby
model
initialization
mongoid
【解决方案1】:
在您的项目模型中:
after_create :init_first_person
def init_first_person
self.people.create(name: 'Initialized User')
end
【解决方案2】:
在你最初提到的问题中
我想在初始化新项目时自动创建一个新的 Person 对象。
(顺便说一句,这是一个非常糟糕的主意),但后来您似乎只想在创建项目时才创建一个人。
在这种情况下,我的建议是在您可以调用的Project 模型中定义自定义方法。不要害怕定义新方法。这比使用回调或覆盖现有的默认方法要好得多。
class Project
def self.create_project_and_user(attributes = {})
# create the user
[... ]
# create the project
create(attributes)
end
end
然后在你的控制器中调用Project.create_project_and_user(...)。
【解决方案3】:
另一种解决方案是创建如下所示的服务对象:
class CreateProjectService
def initialize(params)
@params = params
end
def call
project = Project.create(params[:project])
project.person = Person.create
end
end
然后您可以在控制器中使用此 PORO(普通旧 Ruby 对象),方法是使用请求中的参数创建它并调用它。如果在创建项目时还有其他事情要做,那么您只需将此逻辑添加到服务中。
阅读关于 Rails 应用程序中使用的模式的非常好的文章,您可以找到here。