Rails 3 - 使用params中的值创建并保存具有隐藏字段的对象 - '被调用的id为nil'错误

时间:2012-05-20 15:58:38

标签: ruby-on-rails ruby-on-rails-3 hidden-field

在我的应用程序中,我有控制器从params接收值。之后,我应该使用此值来保存对象(我使用隐藏字段)。但是当我按下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

1 个答案:

答案 0 :(得分:0)

如果出勤未能保存,您将尝试重新呈现包含错误的表单,但未在控制器的@pupil方法中设置create的值 - 因此它将是在视图中调用nil@pupil.id

这可能是您的问题,但是为了确保我们需要知道Attendance是否有任何验证,我们需要查看异常的行号 - 所以如果这不是问题,请发布它们!