使用Simple_form分配多个关联

时间:2013-03-25 00:35:22

标签: ruby-on-rails associations

我理解如何使用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

1 个答案:

答案 0 :(得分: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