我正在尝试在我的Rails 3应用程序中创建一个链接以创建新的嵌套资源,但我无法弄清楚。链接到新的嵌套资源的语法是什么?
解决方案:
确保你在路由文件中正确地嵌套了你的资源。
resources :books do
resources :chapters
end
然后在您的视图脚本中,您可以这样调用它:
<%= link_to 'New Chapter', new_book_chapter_path(@book) %>
Rails路由指南非常有帮助。
注意:如果你收到像Couldn't find Book without an ID
这样的信息,问题不在链接上,而是在你的控制器代码上。
def new
@book = Book.find(params[:book_id]) #instead of :id
@chapter = @book.chapter.new
respond_with(@chapter)
end
|map|
和|book|
。 - Simon Perepelitsa