0
我有一个名为Test的模型,它接受Sub_estted_attributes_for SubTest。一个测试基本上有一个id,并且有多个SubTests与一个单独的Test相关联。Accepts_nested_attributes_for child validation not working
我想验证SubTest的属性是数字。这是我的模型到目前为止。
class Test < ActiveRecord::Base
has_many :sub_tests
accepts_nested_attributes_for :sub_tests
end
class SubTest < ActiveRecord::Base
belongs_to :test
validates :measurement, :numericality => true, :allow_nil => true
end
下面是测试控制器
def create
respond_to do |format|
if @test.save
flash.now[:notice] = "Test Created"
format.html { redirect_to(@test) }
format.xml { render :xml => @test, :status => :created, :location => @test }
format.js
else
flash.now[:error] = "[Error] Test Not Created Because: #{@test.errors.full_messages.join(", ")}"
format.html { render :action => "new" }
format.xml { render :xml => @test.errors, :status => :unprocessable_entity }
format.js
end
end
末
我想创建控制器动作抛出一个错误,如果用户在表单为进入非数字字符串sub_test。
目前,如果我输入非数值为sub_test.measurement,Rails不创建测试或子测试对象(预期的行为)。但由于某些原因没有引发错误,并测试控制器触发create.js.erb部分。
我得到的印象是sub_test.measurement的数值性验证实际上应该发生在测试模型中,但我不确定如何编写测试数字性的自定义验证方法。
在此先感谢!