simple_formを使用して単一のhas_many
関連付けを実装する方法を理解していますが、別のモデルオブジェクトから追加の関連付けを割り当てるにはどうすればよいですか?
私のコードでは、モデルオブジェクトを作成しています@opportunity
。現在、company_id
を割り当てていますが、'user_idも割り当てる必要があります。
@opportunity
_form.html.erb
<% if user_signed_in? %>
<%= simple_form_for([@company, @company.opportunities.build], html: {class: "form-inline"}) do |f| %>
<%= f.error_notification %>
<%= f.input :description, label: false, placeholder: 'Create an opportunity', input_html: { class: "span4" } %>
<%= f.submit 'Submit', class: 'btn btn-small'%>
<% end %>
<% else %>
<%= link_to "Create an Account", new_user_registration_path %>
to contribute
<% end %>
Opportunity_controller.rb
def create
@company = Company.find(params[:company_id])
@opportunity = @company.opportunities.create(params[:opportunity])
respond_to do |format|
if @opportunity.save
format.html { redirect_to company_path(@company), notice: 'Opportunity was successfully created.' }
format.json { render json: @opportunity, status: :created, location: @opportunity }
else
format.html { render action: "new" }
format.json { render json: @opportunity.errors, status: :unprocessable_entity }
end
end
end