2014-09-04 93 views
1

我在rails中有一個簡單的form_for,單擊「add」後不會創建新記錄。我有一個叫做機會的模型,它有一個名爲Contact的嵌套資源。聯繫人的表單是我遇到的問題。我將我的表單與可行的類似嵌套資源進行了比較,但無法找到問題。這裏是我的代碼:form_for not working rails 4.0

聯繫控制器:

def new 
    @contact = Contact.new 
    end 


    def create 

    @opportunity = Opportunity.find(params[:opportunity_id]) 
    @contact = @opportunity.contacts.new(contact_params) 
    if @contact.save 
     redirect_to @opportunity, notice: 'Contact has been added' 
    else 
     redirect_to @opportunity, alert: 'Unable to add Contact' 
    end 
    end 

def contact_params 
    params.require(:contact).permit(:first_name) 
end 

這裏要說的是我有問題的具體形式:

的意見/聯繫人/ new.html.erb:

<div id="new_contact_form"> 

    <%= form_for ([@opportunity, @opportunity.contacts.new]) do |f| %> 
     <div class="field"> 
      <%= f.label "Contact Info:" %> <br /> 
      <%= f.text_area :first_name %> 
     </div> 

     <div class="actions"> 
      <%= f.submit 'Add' %> 
     </div> 
    <% end %> 

    </div> 

請幫忙...謝謝!!!

+2

你需要在你的'new'行動來定義'@ opportunity'實例變量,這是什麼使你的'new.html.erb'。 – vee 2014-09-04 17:17:27

回答

1

更改您的新的動作,這樣的:

def new 
    @opportunity = Opportunity.find(params[:opportunity_id]) 
    @contact = @opportunity.contacts.build 
end 

和您的形式將是:

<%= form_for ([@opportunity, @contact]) do |f| %> 
    // form fields 
<% end %> 
+0

嗨 - 我試過,並得到「第一個參數的形式不能包含零或爲空」與您的代碼的第一行突出顯示... @ mandeep – 2014-09-04 17:57:46

+0

@ user1547174以及這個錯誤告訴我們,無論是機會或形式聯繫是零。我有一個錯誤的答案。嘗試更新回答 – Mandeep 2014-09-04 18:07:10

+0

嗨 - 我仍然得到相同的錯誤... – 2014-09-04 18:24:30