Ruby on Rails 3:link_to 创建新的嵌套资源? [英] Ruby on Rails 3: link_to create new nested resource?

查看:34
本文介绍了Ruby on Rails 3:link_to 创建新的嵌套资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个链接以在我的 Rails 3 应用程序中创建一个新的嵌套资源,但我无法弄清楚.链接到新嵌套资源的语法是什么

I am trying to make a link to create a new nested resource in my Rails 3 application, but I can't figure it out. What is the syntax to link to a new nested resource

确保您的资源正确嵌套在路由文件中.

Make sure you have your resources properly nested in your routes file.

resources :books do
  resources :chapters
end

然后在你的视图脚本中你可以这样调用它:

Then in your view script you can call it like this:

<%= link_to 'New Chapter', new_book_chapter_path(@book) %>

Rails 路由指南很有帮助.

注意:如果您收到类似无法找到没有 ID 的图书 的消息,则问题不在于链接,而在于您的控制器中的代码.

Note: if you get a message like Couldn't find Book without an ID, the problem isn't the link, it's the code in your controller.

def new
  @book = Book.find(params[:book_id]) #instead of :id
  @chapter = @book.chapter.new
  respond_with(@chapter)
end

推荐答案

make changes in routes as

make changes in routes as

map.resources :books do |book|
    book.resources :chapters
end

然后使用这个

link_to new_book_chapter_path(@book)

您也可以使用此链接更好地理解该概念嵌套路由

You can also use this link to understand the concept better Nested Routes

这篇关于Ruby on Rails 3:link_to 创建新的嵌套资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆