简体   繁体   中英

Creating a parent record from a child form in a belongs_to relationship in Rails

I have a has_many and belongs_to relationship like so:

class User < ActiveRecord::Base
  belongs_to :family
end 

class Family < ActiveRecord::Base
  has_many :users
end

When a new user signs up, they fill out a form for the User model. What I want to do is automatically create a new Family record using the User.last_name field from the form. I don't want to prompt them for any Family information in the form.

<% simple_form_for :user do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :email  %>
  <%= f.input :password %>
  <%= f.submit "Create My Account" %>
<% end %>

In the opposite direction, this would be a perfect fit for a nested form. But is that the right solution when you're creating a parent record from a child's form? Or should I create and associate the Family in the User#create action of the controller?

If you're not asking them for any family-information in the form, then you don't need anything in the form. You can do it all in the controller"create" action.

def create
  @user = User.create(user_params)
  @user.create_family(whatever_field: @user.last_name)
  ... etc
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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