[英]Ruby on Rails - model validation
I have a problem with simple model validation. 我对简单的模型验证有疑问。 Entering materials without SKU is getting me error message: 输入没有SKU的物料会收到错误消息:
NoMethodError in Materials#create undefined method `empty?' Materials#create中的NoMethodError创建未定义的方法“空?” for nil:NilClass 对于nil:NilClass
material.rb: material.rb:
class Material < ActiveRecord::Base
validates :sku, :presence => true
end
materials_controler.rb (create part only): materials_controler.rb(仅创建零件):
# POST /materials
# POST /materials.json
def create
@material = Material.new(material_params)
respond_to do |format|
if @material.save
format.html { redirect_to @material, notice: 'Material was successfully created.' }
format.json { render :show, status: :created, location: @material }
else
format.html { render :new }
format.json { render json: @material.errors, status: :unprocessable_entity }
end
end
end
Your @units
instance variable is nil
in create
action. 您的@units
实例变量在create
操作中为nil
。 You should set it the same way as you do in new
or edit
actions after your records fails validation. 记录验证失败后,应使用与new
或edit
操作相同的方式进行设置。
在您的create方法中也定义@units
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.