Rails 3:如何创建新的嵌套资源?

时间:2010-09-24 04:25:08

标签: ruby-on-rails ruby-on-rails-3

此部分的Getting Started Rails Guide种闪烁,因为它没有实现Comments控制器的“新”操作。在我的应用程序中,我有一个包含许多章节的书模型:

class Book < ActiveRecord::Base
  has_many :chapters
end

class Chapter < ActiveRecord::Base
  belongs_to :book
end

在我的路线档案中:

resources :books do
  resources :chapters
end

现在我想实现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

这样做的正确方法是什么?另外,视图脚本(表单)应该是什么样的?

3 个答案:

答案 0 :(得分:121)

首先,你必须在你的章节控制器中找到相应的书,为他建立一个章节。你可以这样做:

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...

希望这有帮助。

答案 1 :(得分:6)

试试@chapter = @book.build_chapter。当你致电@book.chapter时,它是零。你做不到nil.new

编辑:我刚刚意识到这本书很可能有多章......以上是针对has_one的。您应该使用@chapter = @book.chapters.build。章节“空数组”实际上是一个特殊的对象,它响应build以添加新的关联。

答案 2 :(得分:1)

也许是无关的,但是从这个问题的标题,你可能会到这里寻找如何做一些稍微不同的事情。

假设您想要Book.new(name: 'FooBar', author: 'SO'),并且您希望将一些元数据拆分为一个名为readable_config的单独模型,该模型具有多态性,并存储nameauthor多个模型。

您如何接受Book.new(name: 'FooBar', author: 'SO')来构建Book模型以及readable_config模型(我可能会错误地称之为'嵌套资源')

这可以这样做:

class Book < ActiveRecord::Base
  has_one :readable_config, dependent: :destroy, autosave: true, validate: true
  delegate: :name, :name=, :author, :author=, :to => :readable_config

  def readable_config
    super ? super : build_readable_config
  end
end