Rails 3:如何创建新的嵌套资源? [英] Rails 3: How to create a new nested resource?
问题描述
Rails 入门指南 掩盖了这一部分,因为它没有实现Comments 控制器的新"操作.在我的应用程序中,我有一个包含许多章节的书籍模型:
The Getting Started Rails Guide kind of glosses over this part since it doesn't implement the "new" action of the Comments controller. In my application, I have a book model that has many chapters:
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
在我的路由文件中:
resources :books do
resources :chapters
end
现在我想实现章节控制器的新"操作:
Now I want to implement the "new" action of the Chapters controller:
class ChaptersController < ApplicationController
respond_to :html, :xml, :json
# /books/1/chapters/new
def new
@chapter = # this is where I'm stuck
respond_with(@chapter)
end
这样做的正确方法是什么?另外,视图脚本(表单)应该是什么样的?
What is the right way to do this? Also, What should the view script (form) look like?
推荐答案
首先你必须在你的章节控制器中找到相应的书来为他建立一个章节.你可以这样做:
First you have to find the respective book in your chapters controller to build a chapter for him. You can do your actions like this:
class ChaptersController < ApplicationController
respond_to :html, :xml, :json
# /books/1/chapters/new
def new
@book = Book.find(params[:book_id])
@chapter = @book.chapters.build
respond_with(@chapter)
end
def create
@book = Book.find(params[:book_id])
@chapter = @book.chapters.build(params[:chapter])
if @chapter.save
...
end
end
end
在你的表单中,new.html.erb
In your form, new.html.erb
form_for(@chapter, :url=>book_chapters_path(@book)) do
.....rest is the same...
或者你可以试试速记
form_for([@book,@chapter]) do
...same...
希望这会有所帮助.
这篇关于Rails 3:如何创建新的嵌套资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!