2015-03-24 38 views
1

我試圖讓我的CRM應用程序能夠正常工作,並且無法找出破損部分在哪裏。 當試圖創建新的聯繫人時,在鏈接'/ companies/1/contacts/new' 得到了'NoMethodError in Contacts#new'。Rails form_for NoMethodError - 無法找到破損路徑在哪裏

截圖附後,請參閱下面的代碼。請幫忙找錯..

enter image description here

route.rb是:

Rails.application.routes.draw do 

    resources :companies do 
    resources :contacts do 
     member do 
     post :new 
     end 
    end 
    end 

    root 'companies#index' 
end 

聯繫控制器:

class ContactsController < ApplicationController 

    before_action :set_company 

    def index 
    @contacts = Contact.where(company_id: params[:company_id]) 
    end 

    def new; @contact = @company.contacts.new; end 

    def create 
    @contact = @company.contacts.create(contact_params) 
    @contact.save ? redirect_to @company : render :new 
    end 

    private 

    def set_company; @company = Company.find(params[:company_id]); end 

    def contact_params 
    params.require(:contact).permit(:name, :position, :phone, :email) 
    end 
end 

查看: new.html.erb:

<%= render 'form' %> 
<%= link_to 'Back', company_contacts_path %> 

形式助手:

<%= form_for(@contact) do |f| %> 
    <div class="field"> 
    <%= f.label :name %><br> 
    <%= f.text_field :name %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

回答

2

您需要指定公司作爲第一個參數form_for

form_for(@company, @contact) 

然後form_for就能推斷出正確的路徑。