使用嵌套属性和多态关联进行用户验证失败

时间:2015-01-16 16:30:38

标签: ruby-on-rails

这个简单的验证测试失败了:

require 'test_helper'
class UserTest < ActiveSupport::TestCase
  def setup
    @user = User.new(name: "Example User", 
                     email: "user@example.com", 
                     character_attributes: {callsign: "example"},
                     password: "foobar", 
                     password_confirmation: "foobar"
                     )
  end

  test "should be valid" do
    assert @user.valid?, "#{@user.errors.messages}"
  end

end

...收到此消息:character.sociable_id"=>["can't be blank"]

我不明白为什么UserTest中的用户创建无法创建有效的用户。

每个用户has_one :character和每个角色belongs_to用户。

用户模型: User.rb:

class User < ActiveRecord::Base

  attr_accessor :remember_token, :activation_token, :reset_token
  has_one  :character, as: :sociable, dependent: :destroy
  accepts_nested_attributes_for :character
  has_secure_password
  before_validation do
    self.create_character unless character
  end
  before_save do
    self.email.downcase!
  end
  before_create :create_activation_digest
  validates :name, presence: true,
                   length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence:   true,
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }, allow_blank: true
  validates :character, presence: true
  .
  .
end

角色模型: Character.rb:

class Character < ActiveRecord::Base
  belongs_to :sociable, polymorphic: true
  has_many   :posts, dependent: :destroy
  before_save do
    self.callsign.downcase!
  end
  validates :sociable_id, presence: true
  VALID_CALLSIGN_REGEX = /\A[a-z\d\-.\_]+\z/i
  validates :callsign, presence:   true,
                       length:     { maximum: 20 },
                       format:     { with: VALID_CALLSIGN_REGEX },
                       uniqueness: { case_sensitive: false }

end

1 个答案:

答案 0 :(得分:1)

应该是: -

test "should be valid" do
  assert @user.valid? , "#{@user.errors.messages}"
end