2

我有两个相关的模型:

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

如果我保存管理员,如何验证用户是否存在?

更新

这是我的测试:

工厂.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

目前只有第一个管理测试失败,但如果我在管理模型中验证用户的存在,几乎所有测试都会失败。也许我的测试或工厂是错误的?

4

3 回答 3

10

您可以使用validates_associated

class Admin < ActiveRecord::Base
  validates_associated :user
  validates_presence_of :user
end

NOTE:如果要确保关联既存在又保证有效,还需要使用 validates_presence_of。

于 2013-07-03T19:12:40.407 回答
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按预期工作。

于 2013-07-03T20:33:49.870 回答
0

我认为您仍然可以在管理员上使用相同的验证。它也应该适用于关系。

尝试

validates :user, presence: true

于 2013-07-03T19:11:29.750 回答