我在视图中有以下代码:
<%= f.select :user_id, user_all_select_options, :include_blank => '--Select a name-----' %>
它会在顶部显示--Select a name-----
的用户列表。当用户未从列表中选择名称并选择--Select a name-----
时,我会收到错误,因为user_id为空。
作为参考,辅助方法代码如下所示:
def user_all_select_options
User.all.map{ |user| [user.name, user.id] }
end
我的模型如下:
class Parcel < ActiveRecord::Base
attr_accessible :parcel, :received_at, :received_by, :chilled, :courier, :location, :passed_to, :user_id, :user, :content, :localip
validates :user_id, :presence => true
belongs_to :user
end
由于某种原因,验证似乎没有运行,但是如果我从下拉列表中选择用户并为其他字段输入添加验证,则应用程序会正确地向用户显示一条消息,指出哪个字段不正确为空。
有趣的是,如果我将选择下拉列表保留为--Select a name-----
并保留其他验证,则会抛出异常。它不会提示丢失的字段只是错误。
这是错误期间的记录(此记录来自我在位置字段上进行验证状态检查时:
{"utf8"=>"✓", "authenticity_token"=>"wM4KPtoswp3xdv8uU4UasdadNsZi9yFZmk=", "parcel"=>{"user_id"=>"", "received_by"=>"dan", "content"=>"", "chilled"=>"0", "courier"=>"", "location"=>"", "passed_to"=>"", "received_at(3i)"=>"9", "received_at(2i)"=>"2", "received_at(1i)"=>"2013", "received_at(4i)"=>"22", "received_at(5i)"=>"59"}, "commit"=>"Receive this Parcel", "action"=>"create", "controller"=>"parcels"}
我应该从哪里开始寻找?显示的错误是控制器执行的操作,除非检查用户。
parcel控制器创建方法如下所示:
def create
@parcel = Parcel.new(params[:parcel])
@parcel.localip = request.env['REMOTE_ADDR']
@parcel.received_by = @parcel.received_by.upcase
unless @parcel.user.mobilenumber.blank?
UserMailer.parcel_notification(@parcel).deliver
end
respond_to do |format|
if @parcel.save
format.html { redirect_to @parcel, notice: 'Parcel was successfully created.' }
format.json { render json: @parcel, status: :created, location: @parcel }
else
format.html { render action: "new" }
format.json { render json: @parcel.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:1)
当你没有选择用户时你得到例外的原因是这一行
unless @parcel.user.mobilenumber.blank?
由于user_id
未设置,@parcel.user
为nil
,导致异常。
我建议你将其移到@parcel.save
区块内。
def create
@parcel = Parcel.new(params[:parcel])
@parcel.localip = request.env['REMOTE_ADDR']
@parcel.received_by = @parcel.received_by.upcase
respond_to do |format|
if @parcel.save
unless @parcel.user.mobilenumber.blank?
UserMailer.parcel_notification(@parcel).deliver
end
format.html { redirect_to @parcel, notice: 'Parcel was successfully created.' }
format.json { render json: @parcel, status: :created, location: @parcel }
else
format.html { render action: "new" }
format.json { render json: @parcel.errors, status: :unprocessable_entity }
end
end
end