使用Rails嵌套资源
我是rails的新手,我开始使用嵌套资源。 我一直在阅读这个http://guides.rubyonrails.org/routing.html#nested-resources,所以我创建了两个模型,一个产品和一个发件人。 产品有很多发件人。 我的发件人模型是这样的:
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 ,现在rake路线为我提供了所需的所有正确路线
所以当我输入url时
http://localhost:3000/products/1/senders/new
所以我为我的产品创建了一个id = 1的新发件人我得到了这个:
NoMethodError in Senders#new undefined method `senders_path' for #<#:0x00000003e6f408>
为什么我会得到这个未定义的方法,因为它应该为我的产品的发送者提供new.html.erb页面?
请注意,如果您执行了rake routes
,则无法找到您要查找的路线。 这是因为您的senders
路由嵌套在products
。
因此,如果要创建新发件人,则路径应类似于new_product_sender_path(product)
。
因此,要获取特定产品的所有发件人,路径将是product_senders_path(product)
。