2012-06-09 47 views
0

我對rails和編程方面的ruby都很新穎。我正在嘗試開發一個應用程序,但我現在陷入困境。我正在觀看http://railscasts.com/episodes/196-nested-model-form-part-1製作嵌套模型表單,但我有一個錯誤。我的問題細節如​​下;嵌套的模型表單在軌道上不起作用

我有僱主模特,僱主模特has_many面試,以及面試模特has_many customquestions。我正在嘗試創建一個表單,通過它我將收集信息以創建面試。雖然我提出了所有必要的協助,但是當我提交表格時,會引發錯誤,說「Customquestions採訪不能爲空」。我有點確定,這是因爲我錯過了面試控制器中的一些代碼。下面你可以看到我的面試控制器和我用來提交信息的表單模板。

採訪控制器

class InterviewsController < ApplicationController 
    before_filter :signed_in_employer 

    def create 
    @interview = current_employer.interviews.build(params[:interview]) 

    if @interview.save 
     flash[:success] = "Interview created!" 
     redirect_to @interview 
    else 
     render 'new' 
    end 
    end 

    def destroy 
    end 

    def show 
    @interview = Interview.find(params[:id]) 
    end 

    def new 
    @interview = Interview.new 
     3.times do 
    customquestion = @interview.customquestions.build 
    end 
    end 
end 

,我用它來提交信息表:

<%= provide(:title, 'Create a new interview') %> 
<h1>Create New Interview</h1> 

<div class="row"> 
    <div class="span6 offset3"> 
    <%= form_for(@interview) do |f| %> 
    <%= render 'shared/error_messages_interviews' %> 

     <%= f.label :title, "Tıtle for Interview" %> 
     <%= f.text_field :title %> 

     <%= f.label :welcome_message, "Welcome Message for Candidates" %> 
     <%= f.text_area :welcome_message, rows: 3 %> 

     <%= f.fields_for :customquestions do |builder| %> 
     <%= builder.label :content, "Question" %><br /> 
     <%= builder.text_area :content, :rows => 3 %> 
     <% end %> 
     <%= f.submit "Create Interview", class: "btn btn-large btn-primary" %> 
    <% end %> 
    </div> 
</div> 

在採訪模式,我使用accepts_nested_attributes_for :customquestions

採訪型號

class Interview < ActiveRecord::Base 
    attr_accessible :title, :welcome_message, :customquestions_attributes 
    belongs_to :employer 
    has_many :customquestions 
    accepts_nested_attributes_for :customquestions 

    validates :title, presence: true, length: { maximum: 150 } 
    validates :welcome_message, presence: true, length: { maximum: 600 } 
    validates :employer_id, presence: true 
    default_scope order: 'interviews.created_at DESC' 
end 

回答

0

驗證錯誤在自定義問題模型中被提出,因爲(我假設)它是validates :interview_id。問題是,只有在保存父對象(Interview)之前,才能設置interview_id,但在保存面試前運行customquestion驗證。

通過在customquestions模型中添加選項:inverse_of=> :customquestionsbelongs_to :interview,可以讓cusomtquestions知道此依賴關係。

+0

這就解決了我的問題:)謝謝你@cdesrosiers – hayri