模型和嵌套表单 [英] Models and Nested Forms

查看:19
本文介绍了模型和嵌套表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一款可为消费者和企业提供功能的应用.在创建我的模型时,我正在考虑拥有用户(消费者)和业务......每个业务也有用户,但用户不一定属于一个业务.为了减少冗余,我会在用户中收集姓名、电子邮件等信息,并在业务中收集特定的业务信息(地址、电话).

I'm building an app that provides functionality for both consumers and businesses. In creating my models, I'm thinking of having user (consumer) and business...where each business would also have user(s), but users wouldn't necessarily belong to a business. To reduce redundancy I'd collect name, email, etc in User and specific business info (address, phone) in Business.

class Business < ActiveRecord::Base
   belongs_to :user  
end

class User < ActiveRecord::Base
 has_one :business #only if business user, not consumer
end

这是配置所需关系的正确方法吗?

Is this the correct way to configure the desired relationship?

然后,当需要进行商业注册时,是否有可能(以及如何)在我的业务对象先是嵌套表单,然后是用户...所以我按该顺序收集信息?我发现的所有示例/信息都显示了首先捕获用户信息的设置,然后是任何子模型.

Then when it comes time for business registration, is it possible (and how) to have nested forms where my business object is first, then user...so I'm collecting information in that order? All examples/info I've found shows the setup with user info captured first, then any sub-models.

在我下面的例子中,这是否正确:

In my following example, would this be correct:

<%= form_for(@business) do |f| %>
  #grab business info
<%= f.fields_for :user do |ff| %>
 #grab user info

感谢您的时间和帮助.

推荐答案

你需要有

 class Business < ActiveRecord::Base
  belongs_to :user  
 end

 class User < ActiveRecord::Base
  has_one :business #only if business user, not consumer
  attr_accessible :business_attributes
  accepts_nested_attributes_for :business
 end

和形式应该是

 <%= form_for(@user) do |f| %>
  #grab user info
 <%= f.fields_for :business_attributes do |ff| %>
  #grab business info

然后在update方法中使用update_attributes来更新用户

then use update_attributes in update method to update user

这篇关于模型和嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆