Models and Nested Forms

こ雲淡風輕ζ 提交于 2019-12-02 21:20:38

问题


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

Thanks for your time and assistance.


回答1:


You will need to have

 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

and form should be

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

then use update_attributes in update method to update user




回答2:


You mentioned businesses might have several users, so it should be:

class Business < ActiveRecord::Base
  has_many :users
end

User will then belong to a business (optionally)

class User < ActiveRecord::Base
  belongs_to :business
end

In your form, you first call a form for a Business:

form_for @business do |business_form|

Then you can edit business' users:

business_form.fields_for :users do |user_form|

If it's a new business you're creating which does not have any users yet, you can build however many users you want for that business in the controller, so that the users subforms have objects to work with. In your controller:

5.times do
  @business.users.build
end

The above will result in 5 new user subforms for the business.



来源:https://stackoverflow.com/questions/12300619/models-and-nested-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!