With the hope that my consecutive questions are not a problem for anyone, I want to ask for your assistance on how to achieve the creation of two models from one form.
The two associated models are
class Employee < ActiveRecord::Base
attr_accessible :name
belongs_to :company
attr_accessible :company_id
end
class Company < ActiveRecord::Base
attr_accessible :name
has_many :employees
end
and what I want is to create a company when I am creating an employee and the input company doesn't already exist. Without the "when the company doesn't already exist" requirement, this is my code:
employees/_form.html.erb
<%= simple_form_for(@employee) do |f| %>
<%= simple_form_for(@company) do |cf| %>
<%= f.input :name, label: 'Employee Name', :required => true %>
<%= cf.input :title, label: 'Company Name', :required => true %>
<% end %>
<% end %>
and employees_controller.rb
def new
@employee = Employee.new
@company = Company.new
end
[...]
def create
@employee = Employee.new(params[:employee])
@company = Company.new(params[:company])
@employee.company_id = params[:company_id]
respond_to do |format|
if @employee.save
format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
format.json { render json: @employee, status: :created, location: @employee }
else
format.html { render action: "new" }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
This some kind of association between the employee and the company (that of the employee "holding" the company id) but it doesn't create (or, if I understand well, doesn't actually save) the company.
If I go on and add @company.save
before the id assignment, everything seems okay. Is it, however? Shouldn't I render the new company form
and have everything saved after that is submitted?
I have been searching online all day for the solution but in every case the implementation was performed the opposite way: How to create a bunch of employees from a new company form.
Okay, after a lot of experimenting, I 've came down to this:
employees/_form.html.erb
employees_controller.rb
It is slightly more elegant than the answer provided by @RadBrad but also influenced by it.
if you need to know how to actually fill in all the attributes of the
company
model, follow thisThere are lot's of ways to go, here is one:
Then in your EmployeesController: