在我的应用程序中,我有从参数接收值的控制器。之后我应该使用这个值来保存对象(我使用隐藏字段)。但我收到这样的错误:Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
当我按下Create
按钮时。我该如何解决这个问题?
控制器:
# 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