我了解如何使用 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 %>
机会控制器.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