2012-05-20 47 views
0

在我的應用程序中,我有控制器從params接收值。之後,我應該使用這個值來保存對象(我使用隱藏的領域)。但我收到這樣的錯誤:Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id當我推Create按鈕。我該如何解決這個問題?Rails 3 - 創建並保存帶有隱藏字段的對象params - 「被調用的ID爲零」錯誤

控制器:

# encoding: UTF-8 
class AttendancesController < ApplicationController 
    before_filter :authenticate_teachers, :only => [ :new, :create ] 

    def new 
    @teacher_subjects = current_user.teacher.subjects 
    @pupil = get_pupil_from_params(params) 
    @attendance = Attendance.new 
    end 

    def create 
    @teacher_subjects = current_user.teacher.subjects 
    @attendance = Attendance.new(params[:attendance]) 

    if @attendance.save 
     redirect_to journals_path(:class_code => params[:class_code], 
            :subject_name => params[:subject_name]) 
     flash[:success] = "Success!" 
    else 
     flash.now[:error] = @attendance.errors.full_messages 
             .to_sentence :last_word_connector => ", ", 
                :two_words_connector => ", " 
     render 'new' 
    end 
    end 

    private 

    def get_pupil_from_params(params) 
     pupil = Pupil.where("id = ?", params[:p_id]).first 
    end  
end 

查看

<%= form_for @attendance, :html => {:class => "form-horizontal"} do |f| %> 
    <%= field_set_tag do %> 
    <%= hidden_field_tag :class_code, params[:class_code] %> 
    <%= hidden_field_tag :subject_name, params[:subject_name] %> 
    <%= f.hidden_field :pupil_id, :value => @pupil.id %> 

    <div class="control-group"> 
     <%= f.label :visited, "Did pupil visit lesson?", :class => "control-label" %> 
     <div class="controls"> 
     <%= label_tag nil, nil, :class => "radio" do %> 
      <%= f.radio_button :visited, true %> 
      Yes 
     <% end %> 

     <%= label_tag nil, nil, :class => "radio" do %> 
      <%= f.radio_button :visited, false %> 
      No 
     <% end %> 
     </div> 
    </div> 

    <%= f.submit "Create", :class => "btn btn-large btn-success" %> 
    <% end %> 
<% end %> 

後我把 '創建' 按鈕,我得到這樣的哈希:

{"utf8"=>"✓", 
"authenticity_token"=>"kgNoJfivDEzqpLJYF5QK9vQS99Cq9app5ujPDC4lKKI=", 
"class_code"=>"11v", 
"subject_name"=>"Math", 
"attendance"=>{"pupil_id"=>"1"}, 
"commit"=>"Create"} 

我的模型:

class Attendance < ActiveRecord::Base 
    belongs_to :pupil 
    belongs_to :lesson 

    validates :pupil_id, :presence => { :message => "should exist" } 

    validates :lesson_id, :presence => { :message => "should exist" } 

    validates :visited, 
       :inclusion => { :in => [true, false], 
           :message => "should be chosen" 
          } 
end 

回答

0

如果出席率未能保存,您將嘗試重新渲染帶有錯誤的表單,但您沒有在控制器的create方法中設置@pupil的值 - 因此在視圖中調用@pupil.id時將爲nil

這可能是您的問題,但要確定我們需要知道,如果Attendance有任何驗證,我們需要查看例外的行號 - 所以如果這不是問題,請發佈它們!

+0

我添加了我的模型! – ExiRe

+0

在我看來,你的出勤率將無法保存,因爲它沒有設置課程ID ... – Russell

相關問題