1

RubyonRailsでシンプルなソーシャルネットワークを作っています。サインアップ時にプロファイル名に特定の文字の制限を追加したかったのです。したがって、私のUser.rbファイルには、次のものがあります。

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me,
                  :first_name, :last_name, :profile_name
  # attr_accessible :title, :body

  validates :first_name, presence: true
  validates :last_name, presence: true

  validates :profile_name, presence: true,
                           uniqueness: true,
                           format: {
                             with: /^[a-zA-Z0-9_-]+$/,
                             message: "must be formatted correctly."
                           }
  has_many :statuses

  def full_name
    first_name + " " + last_name
  end
end

私はそれが機能することを検証するためにテストを設定しました、そしてこれはテストが何であるかです:

test "user can have a correctly formatted profile name" do
user = User.new(first_name: '******', last_name: '****', email: '********@gmail.com')
user.password = user.password_confirmation = '**********'
user.profile_name = '******'
assert user.valid?

終わり

テストを実行すると、assert user.valid?回線に問題があるというエラーが表示され続けます。だから私は私のでいくつかの構文を台無しにしたと思っていますwith: /^[a-zA-Z0-9_-]+$/

私が得ているエラーは1) Failure: test_user_can_have_a_correctly_formatted_profile_name(UserTest) [test/unit/user_test.rb:40]:

しかし、40行目には、このコードが含まれていますassert user.valid?

どんな助けでも大歓迎です:)

4

1 に答える 1

0

だから私は正規表現でいくつかの構文を台無しにしたと思っています。

構文は問題ありません。

ただし、エラーメッセージには、一致しないプロファイル名を使用していることが明確に示されています。

スペースなど、プロファイル名に他の文字を使用していますか?または期間?

このようにしてみてください:

/^[a-zA-Z0-9_-]+$/.match "foobar" #=> #<MatchData "foobar">

データが一致しない場合は、nilになります。

/^[a-zA-Z0-9_-]+$/.match "foo bar" #=> nil
于 2013-01-05T00:58:26.587 に答える