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 %>

机会控制器.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 回答