And*_*rew 65 ruby-on-rails ruby-on-rails-3
在入门的Rails指南那种掩盖了这一部分,因为它没有实现评论控制器的"新"行动.在我的应用程序中,我有一个书模型,有很多章节:
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
Run Code Online (Sandbox Code Playgroud)
在我的路线文件中:
resources :books do
resources :chapters
end
Run Code Online (Sandbox Code Playgroud)
现在我想实现Chapters控制器的"新"动作:
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
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?此外,视图脚本(窗体)应该是什么样的?
dom*_*esz 122
首先,你必须在章节控制器中找到相应的书,为他建立一个章节.你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
在您的表单中,new.html.erb
form_for(@chapter, :url=>book_chapters_path(@book)) do
.....rest is the same...
Run Code Online (Sandbox Code Playgroud)
或者你可以试试速记
form_for([@book,@chapter]) do
...same...
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
试试@chapter = @book.build_chapter
.当你打电话时@book.chapter
,它是零.你做不到nil.new
.
编辑:我刚刚意识到这本书很可能有多章......以上是针对has_one的.你应该用@chapter = @book.chapters.build
.章节"空数组"实际上是一个特殊的对象,它响应build
添加新的关联.
归档时间: |
|
查看次数: |
35085 次 |
最近记录: |