Ruby on rails 嵌套对象并验证
我有一个嵌套对象,它是一种用户类型(比如Sub)。我假设在保存Sub时,用户验证也会运行,但显然不会?创建Sub时如何在User中运行所有验证?验证确实从继承的模型运行 这里有一个测试用例显示它是有效的 测试用例迁移:Ruby on rails 嵌套对象并验证,ruby-on-rails,Ruby On Rails,我有一个嵌套对象,它是一种用户类型(比如Sub)。我假设在保存Sub时,用户验证也会运行,但显然不会?创建Sub时如何在User中运行所有验证?验证确实从继承的模型运行 这里有一个测试用例显示它是有效的 测试用例迁移: class CreateUser < ActiveRecord::Migration def self.up create_table :users do |t| t.column :name,:string t.column :emai
class CreateUser < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :name,:string
t.column :email, :string
t.timestamps
end
end
def self.down
drop_table :users
end
end
class CreateUser
测试模型:
class User < ActiveRecord::Base
validates_presence_of :name
end
class Sub < User
validates_presence_of :email
end
class用户
测试用例:
创建没有名称或电子邮件的子项时,应使用名称保存失败,电子邮件不能为空
>> b = Sub.create()
=> #<Sub id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
>> b.save
=> false
>> b.errors
=> #<ActiveRecord::Errors:0x2457458 @errors={"name"=>["can't be blank"], "email"=>["can't be blank"]}, @base=#<Sub id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>>
>b=Sub.create()
=> #
>>拯救
=>错误
>>错误
=>#[“不能为空”],“电子邮件”=>[“不能为空”]},@base=>
创建没有电子邮件的sub,保存应失败,电子邮件不能为空
>> b = Sub.create(:name=>'test')
=> #<Sub id: nil, name: "test", email: nil, created_at: nil, updated_at: nil>
>> b.save
=> false
>> b.errors
=> #<ActiveRecord::Errors:0x243865c @errors={"email"=>["can't be blank"]}, @base=#<Sub id: nil, name: "test", email: nil, created_at: nil, updated_at: nil>>
>> b = Sub.create(:email=>'test')
=> #<Sub id: nil, name: nil, email: "test", created_at: nil, updated_at: nil>
>> b.save
=> false
>> b.errors
=> #<ActiveRecord::Errors:0x2429594 @errors={"name"=>["can't be blank"]}, @base=#<Sub id: nil, name: nil, email: "test", created_at: nil, updated_at: nil>>
>b=Sub.create(:name=>'test')
=> #
>>拯救
=>错误
>>错误
=>#[“不能为空”]},@base=#>
创建没有名称的子项时,保存应失败,且名称不能为空
>> b = Sub.create(:name=>'test')
=> #<Sub id: nil, name: "test", email: nil, created_at: nil, updated_at: nil>
>> b.save
=> false
>> b.errors
=> #<ActiveRecord::Errors:0x243865c @errors={"email"=>["can't be blank"]}, @base=#<Sub id: nil, name: "test", email: nil, created_at: nil, updated_at: nil>>
>> b = Sub.create(:email=>'test')
=> #<Sub id: nil, name: nil, email: "test", created_at: nil, updated_at: nil>
>> b.save
=> false
>> b.errors
=> #<ActiveRecord::Errors:0x2429594 @errors={"name"=>["can't be blank"]}, @base=#<Sub id: nil, name: nil, email: "test", created_at: nil, updated_at: nil>>
>b=Sub.create(:email=>'test')
=> #
>>拯救
=>错误
>>错误
=>#[“不能为空”]},@base=#>
创建具有名称和电子邮件的sub,保存应成功
>> b = Sub.create(:email=>'test',:name=>'test')
=> #<Sub id: 4, name: "test", email: "test", created_at: "2009-10-15 22:27:53", updated_at: "2009-10-15 22:27:53">
>> b.save
=> true
>b=Sub.create(:email=>'test',:name=>'test')
=> #
>>拯救
=>正确
Oops。我的意思是我有Sub