Rails nested form for belongs_to
- by user1232533
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