2012-08-25 191 views
1

我是rails新手,我開始使用嵌套資源。我一直在閱讀http://guides.rubyonrails.org/routing.html#nested-resources,所以我創建了2個模型,一個產品和一個發件人。產品有許多發件人。我的發件人模式是這樣的:使用Rails嵌套資源

class Sender < ActiveRecord::Base 
    attr_accessible :product_id, :email, :name 

    belongs_to :product 
end 

我的產品是這

class Product < ActiveRecord::Base 
    attr_accessible :name, :price 

    #Relationships ! 
    has_many :senders, dependent: :destroy 
end 
在我的routes.rb

resources :products do 
    resources :senders 
    end 

現在耙路線給了我應該的沒事路線,根據到http://guides.rubyonrails.org/routing.html#nested-resources

所以當我輸入網址

http://localhost:3000/products/1/senders/new 

所以我創建了一個新的寄件人我的產品與ID = 1,我得到這樣的:

NoMethodError in Senders#new 

undefined method `senders_path' for #<#<Class:0x00000003fcf9d8>:0x00000003e6f408> 

爲什麼會出現這種不確定的方法,因爲它應該給我的new.html.erb頁該產品的發件人?

回答

0

請注意,如果您沒有rake routes,則找不到要查找的路線。這是因爲您的路線senders嵌套在products之內。

因此,如果您要創建一個新的發件人,路徑應該是類似new_product_sender_path(product)

因此,要獲得特定產品的所有發件人,路徑將爲product_senders_path(product)