我有两个相关的模型:
class User < ActiveRecord::Base
belongs_to :role, dependent: :destroy, polymorphic: true
validates :role, presence: true
end
class Admin < ActiveRecord::Base
has_one :user, as: :role
attr_accessible :user_attributes
accepts_nested_attributes_for :user
end
如果我保存管理员,如何验证用户是否存在?
更新
这是我的测试:
factories.rb
FactoryGirl.define do
sequence :email do |n|
"foo#{n}@example.com"
end
factory :user do
email
password "secret12"
password_confirmation "secret12"
factory :admin_user do
association :role, factory: :admin
end
end
factory :admin do
first_name "Max"
last_name "Mustermann"
end
end
user_spec.rb
require "spec_helper"
describe User do
let(:user) { FactoryGirl.build(:user) }
let(:admin) { FactoryGirl.build(:admin_user) }
describe "sign up" do
it "should not be valid without associated role" do
user.should_not be_valid
end
it "should be valid with associated role" do
admin.should be_valid
end
end
end
admin_spec.rb
require "spec_helper"
describe Admin do
let(:admin_base) { FactoryGirl.build(:admin) }
let(:admin_user) { FactoryGirl.build(:admin_user).admin }
describe "sign up" do
it "should not be possible without associated user" do
admin_base.should_not be_valid
end
end
it "should have a first name" do
admin_user.first_name = ""
admin_user.should_not be_valid
end
it "should have a last name" do
admin_user.last_name = ""
admin_user.should_not be_valid
end
it "should create a correct full name" do
admin_user.full_name.should == "Max Mustermann"
end
end
此刻只有第一个管理员测试失败,但如果我在管理模型中验证用户的存在,则几乎所有测试都会失败。也许我的测试或工厂都错了?
答案 0 :(得分:8)
您可以使用validates_associated。
class Admin < ActiveRecord::Base
validates_associated :user
validates_presence_of :user
end
NOTE:
如果您想确保关联存在且保证有效,您还需要使用validates_presence_of。
答案 1 :(得分:0)
我认为你仍然可以在admin上使用相同的验证。它也应该与关系一起工作。
尝试
validates :user, presence: true
答案 2 :(得分:0)
我的工厂错了。他们应该看起来像:
FactoryGirl.define do
sequence :email do |n|
"foo#{n}@example.com"
end
factory :user_base, class: User do
email
password "secret12"
password_confirmation "secret12"
factory :user_with_role do
association :role, factory: :admin
end
end
factory :admin_base, class: Admin do
first_name "Max"
last_name "Mustermann"
factory :admin do
association :user, factory: :user_base, strategy: :build
end
end
end
现在validates :user, presence: true
上的测试按预期工作。