0

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
4

1 に答える 1

1

ユーザーがログインしていると仮定すると、コントローラーのアクションを次のように変更できます。

def create
  @company = Company.find(params[:company_id])
  @opportunity = @company.opportunities.new(params[:opportunity]) # new instead of create
  @opportunity.user = current_user # new

  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
于 2013-03-25T01:18:32.180 に答える