作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Getting Started Rails Guide有点掩盖了这部分,因为它没有实现评论 Controller 的"new"操作。在我的应用程序中,我有一个包含许多章节的书籍模型:
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
在我的路线文件中:
resources :books do
resources :chapters
end
现在我想实现章节 Controller 的"new"操作:
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
执行此操作的正确方法是什么?另外, View 脚本(表单)应该是什么样子?
最佳答案
首先,你必须在章节 Controller 中找到相应的书来为他构建一个章节。您可以像这样执行操作:
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
form_for(@chapter, :url=>book_chapters_path(@book)) do
.....rest is the same...
或者你可以尝试简写
form_for([@book,@chapter]) do
...same...
关于ruby-on-rails - rails 3 : How to create a new nested resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784183/
我是一名优秀的程序员,十分优秀!