2011-05-09 1 views
12

내 중첩 된 모델 양식이 첫 번째 레벨에서 잘 작동합니다. 하지만 accepts_nested_attributes_for를 사용하여 여러 단계로 갈 수 있다는 인상하에있었습니다. 그러나 아래 코드를 시도하면 "Image"속성이 최상위 "Question"모델에 첨부되고 알 수없는 속성 "Image"오류가있는 양식 제출시 중단됩니다.레일 3 중첩 된 모델 양식, 2 단계 깊이로 accepts_nested_attributes_for 사용

양식 데이터를 사용하여 손으로 직접 삽입 할 수 있지만 레일스가 자동으로 처리 할 수 ​​있다면 명백한 이유가 있습니다.

내가 뭘 잘못하고 있니? 나는 변화를 시도했다. af | "fields for : image do"를 고유 한 이름으로 변경했지만 아무런 효과가 없었습니다.

모델 :

class Question < ActiveRecord::Base 
    has_one :answer 
    accepts_nested_attributes_for :answer 
end 

class Answer < ActiveRecord::Base 
    belongs_to :question 
    has_one :image 
    accepts_nested_attributes_for :image 
end 

class Image < ActiveRecord::Base 
    belongs_to :answer 
end 

컨트롤러 :

def new 
    @question = Question.new 
    answer = @question.build_answer 
    image = answer.build_image 

    @case_id = params[:id] 

    render :layout => 'application', :template => '/questions/form' 
end 

def create 
    question_data = params[:question] 
    @question = Question.new(question_data) 
    if @question.save 
    ... 
end 

보기 :

= form_for @question, :html => {:multipart => true} do |f| 

    = f.label :text, "Question Text:" 
    = f.text_area :text, :rows => 7 

    %br 
    %br 

    =f.fields_for :answer, do |af| 
    = af.label :body, "Answer Text:" 
    = af.text_area :body, :rows => 7 

    %br 
    %br 

    = f.fields_for :image do |af| 
     = af.label :title, "Image Title:" 
     = af.text_field :title 

     %br 

     = af.label :file, "Image File:" 
     = af.file_field :file 

     %br 

     = af.label :caption, "Image Caption:" 
     = af.text_area :caption, :rows => 7 

    = hidden_field_tag("case_id", value = @case_id) 

    = f.submit 

답변

8

난 당신이 약간 혼합 형태 변수를 가지고 생각합니다. 그것은해야한다 :

= form_for @question, :html => {:multipart => true} do |f| 

    = f.label :text, "Question Text:" 
    = f.text_area :text, :rows => 7 

    %br 
    %br 

    =f.fields_for :answer, do |af| 
    = af.label :body, "Answer Text:" 
    = af.text_area :body, :rows => 7 

    %br 
    %br 

    = af.fields_for :image do |img_form| 
     = img_form.label :title, "Image Title:" 
     = img_form.text_field :title 

     %br 

     = img_form.label :file, "Image File:" 
     = img_form.file_field :file 

     %br 

     = img_form.label :caption, "Image Caption:" 
     = img_form.text_area :caption, :rows => 7 

    = hidden_field_tag("case_id", value = @case_id) 

    = f.submit 

회전에 af.fields_for ... do |img_form| 급부상하는 form_for ... do |f|f.fields_for ... do |af| 급부상하는 방법을 알 수 있습니다.

키는 두 번째 fields_for입니다. f.fields_for :image do |img_form| 대신 af.fields_for :image do |img_form|이어야합니다.

+1

고맙습니다. 그 문제가 해결되었습니다. 지금 내가 가진 유일한 문제는 양식을 제출할 때 양식 오류 "답변 질문을 비워 둘 수 없습니다."입니다. 나는 "Answer"에 required_id라는 필수 입력란이 있기 때문에 이것이 채워지지 않을 수도있는 것 같아요. 어떤 아이디어? – LennonR

+2

맞습니다. 이것은 자식 객체 ('Answer')를 저장하려고 할 때 부모 객체 ('Question')가 새로운 레코드이고 아직 존재하지 않기 때문에 (즉, id를 가지고 있지 않기 때문에) 발생합니다. question_id 나 컨트롤러에서 검증을 제거 할 수 있습니다. 먼저 부모 객체 ('@ question.save')와 자식 ('@question.answers << @ answer')을 저장하십시오. 뭔가 그걸로 ... 자세한 내용은 체크 아웃이 [문서] (http://hobocentral.net/blog/2008/04/29/activerecord-behaviour-with-associations/). HTH – mbreining

+0

정말 그걸 알아낼 수 없습니까? 다음 Railscast (Rails 2.3에도 불구하고)에서 저자는 간단한 @ survey.new/@ survey.save를 사용하여 수행하려는 작업을 수행합니다. [link] (http://railscasts.com/episodes/196-nested-model-form-part-1) 그에게 Rails는 모든 것을 알아 냈고 올바르게 연결했습니다. 레일스 3은 더 이상 이것을 처리하지 못합니까? 그의 프로젝트에 대한 github 소스 코드는 다음과 같습니다. [link] (https://github.com/ryanb/railscasts-episodes/tree/master/episode-196/surveysays) 아니면 다른 것을하고 있습니까? – LennonR

관련 문제