Rails nested form for belongs_to
Posted
by
user1232533
on Stack Overflow
See other posts from Stack Overflow
or by user1232533
Published on 2012-03-24T20:41:58Z
Indexed on
2012/03/24
23:29 UTC
Read the original article
Hit count: 187
ruby-on-rails
|nested-forms
I'm new to rails and have some troubles with creating a nested form.
My models:
class User < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company, :reject_if => :all_blank
end
class Company < ActiveRecord::Base
has_many :users
end
Now i would like to create a new company from the user sign_up page (i use Devise btw) by given only a company name. And have a relation between the new User and new Company.
In the console i can create a company for a existing User like this:
@company = User.first.build_company(:name => "name of company")
@company.save
That works, but i can't make this happen for a new user, in my new user sign_up form i tried this (i know its wrong by creating a new User fist but im trying to get something working here..):
<%= simple_form_for(resource, :as => resource_name, :html => { :class => 'form-horizontal' }, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="inputs">
<%
@user = User.new
company = @user.build_company()
%>
<% f.fields_for company do |builder| %>
<%= builder.input :name, :required => true, :autofocus => true %>
<% end %>
<%= f.input :email, :required => true, :autofocus => true %>
<%= f.input :password, :required => true %>
<%= f.input :password_confirmation, :required => true %>
</div>
<div class="form-actions">
<%= f.button :submit, :class => 'btn-primary', :value => 'Sign up' %>
</div>
I did my best to google for a solution/ example.. found some nested form examples but it's just not clear to me how to do this.
Really hope somebody can help me with this. Any help on this would be appreciated.
Thanks in advance!
Greets, Daniel
© Stack Overflow or respective owner