简体   繁体   English

一种形式生成两个模型

[英]One form to generate two models

I'm new to rails and I'm facing a problem that I couldn't find a solution yet. 我是Rails的新手,现在遇到的问题是我找不到解决方案。

I want to have a single page form that will generate two different models. 我希望有一个页面表单,它将生成两个不同的模型。 Is that possible? 那可能吗? For example, when the user presses the submit button, some of the input will be used to generate the User model and other inputs will be used to generate a Pharmacy model. 例如,当用户按下提交按钮时,某些输入将用于生成用户模型,而其他输入将用于生成药房模型。

Thanks in advance 提前致谢

You will use a form_for and pass in the parent object. 您将使用form_for并传入父对象。 Then, when you get to the fields for the other object, you can use the fields_for method and pass in the other object. 然后,当您到达另一个对象的字段时,可以使用fields_for方法并传入另一个对象。 Then in the model you can do something like: 然后,在模型中,您可以执行以下操作:

def pharmacy_attributes=(attributes)
  @pharmacy = Pharmacy.create(attributes)
  self.pharmacy = @pharmacy
  save
end

If you are using rails 4 you will have to allow the nested attributes in the controller and add accepts_nested_attributes_for :pharmacy to the user model if that is the way your relationships are set up. 如果使用的是rails 4,则必须在控制器中允许嵌套属性,并在用户模型中添加accepts_nested_attributes_for :pharmacy (如果这是建立关系的方式)。

Take a look at the following code climate blog post: 看一下以下代码气候博客文章:

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

Of particular interest will be section: "3. Extract Form Objects" 特别有趣的是以下部分:“ 3.提取表单对象”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM