2013-03-25 58 views
0

我瞭解如何使用simple_form實現一個單一的has_many關聯,但是如何從另一個模型對象指定一個附加關聯?指定與Simple_form的多個關聯

在我的代碼中,我創建了模型對象@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

假設你的用戶登錄時,你可以改變你的控制器動作如下:

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