Rails 3 : 새 중첩 리소스를 만드는 방법은 무엇입니까?
는 레일 가이드 시작하기 는 댓글 컨트롤러의 "새"동작을 구현하지 않기 때문에이 부분에 글로스의 종류. 내 응용 프로그램에는 많은 장이있는 책 모델이 있습니다.
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
내 경로 파일에서 :
resources :books do
resources :chapters
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 < 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...
도움이 되었기를 바랍니다.
시도해보십시오 @chapter = @book.build_chapter
. 를 호출하면 @book.chapter
nil입니다. 당신은 할 수 없습니다 nil.new
.
EDIT: I just realized that book most likely has_many chapters... the above is for has_one. You should use @chapter = @book.chapters.build
. The chapters "empty array" is actually a special object that responds to build
for adding new associations.
Perhaps unrelated, but from this question's title you might arrive here looking for how to do something slightly different.
Lets say you want to do Book.new(name: 'FooBar', author: 'SO')
and you want to split some metadata into a separate model, called readable_config
which is polymorphic and stores name
and author
for multiple models.
How do you accept Book.new(name: 'FooBar', author: 'SO')
to build the Book
model and also the readable_config
model (which I would, perhaps mistakenly, call a 'nested resource')
This can be done as so:
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
참고URL : https://stackoverflow.com/questions/3784183/rails-3-how-to-create-a-new-nested-resource
'Program Tip' 카테고리의 다른 글
Convert.ToBoolean 및 Boolean.Parse는 0과 1을 허용하지 않습니다. (0) | 2020.11.17 |
---|---|
django의 auth_user.username이 varchar (75)가 될 수 있습니까? (0) | 2020.11.17 |
Python 패키지 내부에서 (정적) 파일을 읽는 방법은 무엇입니까? (0) | 2020.11.17 |
변수에서 대소 문자 구분을 무시하는 Windows 배치 명령 (0) | 2020.11.17 |
Blob에 저장된 미디어 파일의 콘텐츠 유형 설정 (0) | 2020.11.17 |