Ok, I’m able to write to 3 models in 1 form. The code creates a brand
new record in each of the three tables and writes the corresponding
account_id where it’s supposed to be. Everything works well, except one
thing.
PROBLEM: “company_id” it’s not being written in the “users” table.
“account_id” writes in the “companies” and “users” table.
It’s just the “company_id” that doesn’t get saved.
Here are the models.
Account
has_many users
has_many companies
accepts_nested_attributes_for :companies
accepts_nested_attributes_for :users
Company
belongs_to account (account_id)
has_many users
accepts_nested_attributes_for :users
User
belongs_to account (account_id)
belongs_to company (company_id)
This is what I have in the accounts_controller.rb
def new
@account = Account.new
@account.companies.build
@account.users.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @account }
end
end
def create
@account = Account.new(params[:account])
if @account.save
redirect_to(@account, :notice => ‘User was successfully
created.’)
else
render :action => “new”
end
end
This is a simplified version of the form
<%= form_for @account do |account_form| %>
<% account_form.fields_for :users do |user_form| %>
<%= user_form.label :first_name %> <%= user_form.text_field
:first_name %>
<%= user_form.label :last_name %> <%= user_form.text_field :last_name
%>
<%= user_form.label :email %>
<%= user_form.text_field :email %>
<%= user_form.label :username %>
<%= user_form.text_field :username %>
<% end %>
<% account_form.fields_for :companies do |company_form| %>
<%= company_form.label :name, 'Company name' %>
<%= company_form.text_field :name %>
<% end %>
<%= account_form.submit %>
<% end %>
---------------------------------------------------------------