Ruby on rails Rails 3:如何创建新的嵌套资源?
由于它没有实现Comments控制器的“new”操作,所以这一部分被掩盖了。在我的应用程序中,我有一个包含许多章节的图书模型:Ruby on rails Rails 3:如何创建新的嵌套资源?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,由于它没有实现Comments控制器的“new”操作,所以这一部分被掩盖了。在我的应用程序中,我有一个包含许多章节的图书模型: class Book < ActiveRecord::Base has_many :chapters end class Chapter < ActiveRecord::Base belongs_to :book end 现在,我想实现控制器的“新建”操作: class ChaptersController < ApplicationCon
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
现在,我想实现控制器的“新建”操作:
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
class ChaptersController
正确的方法是什么?另外,视图脚本(表单)应该是什么样子?试试
@chapter=@book.build\u chapter
。当你调用@book.chapter
时,它是零。您不能执行无。新建
编辑:我刚刚意识到这本书很可能有很多章节。。。以上是一个例子。您应该使用
@chapter=@book.chapters.build
。章节“空数组”实际上是一个特殊的对象,用于响应构建
以添加新关联。首先,您必须在章节控制器中找到相应的书籍,以便为其构建章节。您可以这样做:
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
或者你可以试试速记
form_for([@book,@chapter]) do
...same...
希望这能有所帮助。也许不相关,但从这个问题的标题来看,您可能会来到这里,寻找如何做一些稍微不同的事情 假设您想要执行
Book.new(名称:'FooBar',作者:'SO')
,并且您想要将一些元数据拆分为一个单独的模型,称为readable\u config
,它是多态的,存储多个模型的name
和author
您如何接受Book.new(名称:'FooBar',作者:'SO')
来构建Book
模型以及readable\u 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
classbook:可读的\u配置
def可读配置
超级的?超级:构建\u可读\u配置
结束
结束
要重构代码,还可以使用get_book方法查找book@book=book.find(params[:book_id]),然后将此方法用作before过滤器。这是因为您在chapter controller中实现的任何方法都需要它所属的book对象。Re:上面的注释,如果您有book的多个子对象,您需要将get\u book
方法重构为bookheloper
和include bookheloper
在您的books控制器和books相关控制器中。这不会对db创建额外的select查询?您指的是@ArnoldRoa什么?
form_for([@book,@chapter]) do
...same...
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