gpt4 book ai didi

ruby-on-rails - rails 3 : How to create a new nested resource?

转载 作者:行者123 更新时间:2023-12-03 05:33:40 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com