書き方がルールに則っていないかとおもいます。
波カッコを外す。スペースを加える。関係ないけどインデントは半角スペース2つ。
Ruby
1class User < ApplicationRecord
2 validates :name, presence: true
3 validates :email, presence: true, uniqueness: true
4end
また公式のページを見ながら設定したほうが色々と幸せになれます。
RailsGuide:バリデーション
とりあえず実行してみました。
ruby
1rails new test-app
2rails model name:string email:string
3rails db:migrate
4#作成されたapp/models/user.rbに上記バリデーションを追加
5rails c
6
irb(main):001:0> user1 = User.new(name:'',email:'1@gmail.com')
(0.8ms) SELECT sqlite_version(*)
=> #<User id: nil, name: "", email: "1@gmail.com", created_at: nil, updated_at: nil>
irb(main):002:0> user1.save
(0.1ms) begin transaction
User Exists? (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "1@gmail.com"], ["LIMIT", 1]]
(0.0ms) rollback transaction
=> false
irb(main):003:0> user2 = User.new(name:'aaaaa',email:'')
=> #<User id: nil, name: "aaaaa", email: "", created_at: nil, updated_at: nil>
irb(main):004:0> user2.save
(0.1ms) begin transaction
User Exists? (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", ""], ["LIMIT", 1]]
(0.1ms) rollback transaction
=> false
irb(main):005:0> user1 = User.new(name:'あああ',email:'1@gmail.com')
=> #<User id: nil, name: "あああ", email: "1@gmail.com", created_at: nil, updated_at: nil>
irb(main):006:0> user1.save
(0.1ms) begin transaction
User Exists? (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "1@gmail.com"], ["LIMIT", 1]]
User Create (1.0ms) INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "あああ"], ["email", "1@gmail.com"], ["created_a "2020-03-09 11:46:44.041319"], ["updated_at", "2020-03-09 11:46:44.041319"]]
(0.9ms) commit transaction
=> true
irb(main):007:0> user1 = User.new(name:'iii',email:'1@gmail.com')
=> #<User id: nil, name: "iii", email: "1@gmail.com", created_at: nil, updated_at: nil>
irb(main):008:0> user1.save
(0.1ms) begin transaction
User Exists? (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "1@gmail.com"], ["LIMIT", 1]]
(0.0ms) rollback transaction
=> false
期待する動きとなっているので、バリデーション自体は問題ないかと思います。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/03/09 09:40
2020/03/09 09:41 編集
2020/03/09 09:45
2020/03/09 09:47
2020/03/09 10:18
2020/03/09 12:07
2020/03/09 12:24