私の連続した質問が誰にとっても問題ではないことを願って、1 つのフォームから 2 つのモデルを作成する方法を教えてください。
関連する 2 つのモデルは次のとおりです。
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
私が望むのは、従業員を作成していて、入力会社がまだ存在していないときに会社を作成することです。「会社がまだ存在しない場合」の要件がない場合、これが私のコードです。
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 %>
と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
これは、従業員と会社の間のある種の関連付け (従業員が会社 ID を「保持」すること) ですが、会社を作成しません (または、私がよく理解している場合は、実際には保存しません)。
id の割り当ての前に追加すると@company.save
、すべて問題ないように見えます。しかし、そうですか?をレンダリングして、new company form
送信後にすべてを保存するべきではありませんか?
私は一日中オンラインで解決策を探していましたが、いずれの場合も実装は逆の方法で行われました。新しい会社形態から多数の従業員を作成する方法です。