简体   繁体   English

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

[英]Failing user validation with nested attributes and polymorphic association

This simple validation test is failing: 这个简单的验证测试失败了:

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

...with this message: character.sociable_id"=>["can't be blank"] ...显示以下消息: character.sociable_id"=>["can't be blank"]

I don't understand why the user creation in UserTest is failing to make a valid User. 我不明白为什么UserTest中的用户创建无法创建有效的User。

Each User has_one :character and each Character belongs_to a User. 每个用户has_one :character ,每个字符belongs_to一个User。

The User model: User.rb: 用户模型: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

The Character model: Character.rb: 角色模型: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

It should be:- 它应该是:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM