LoginSignup
0
0

More than 5 years have passed since last update.

DBに保存する値を検証する

Posted at

DBに保存する値を検証する

app/models/entry.rb
class Entry < ActiveRecord::Base
# contentが空でないことを検証する、と宣言する
validates_presense_of :content
end
entry_with_content = Entry.new(:contet => "a message for you")
#contentがからでないため、検証結果は真となる
entry_with_content.save #=> true
#バリデーションにパスしているため保存される
entry_with_content.new_record? #=> false
entry_without_content = Entry.new
#contentが空であるため、検証結果は偽となる
entry_eithout_content.save #=> false
#検証結果が偽であるため保存はされない
entry_eithout_content.new_record? #=> true

保存せずにバリデーションを行う

entry_with_content = Entry.new(:content => "a message for you")
#contentがからでないため、検証結果は真となる
entry_with_content.valid? #=> true
#バリデーションにパスしていても保存はされていない
entry_with_content.new_record? #=> true


バリデーションを行わず保存する

entry_eithout_content = Entry.new
#contentが空であるため、検証結果は偽となる
entry_without_content.valid? #=> false
#当然ながら保存はされていない
entry_without_content.new_record? #=> true

バリデーションのエラーメッセージを取得する

entry_without_content = Entry.new
entry_without_content.valid? #=> false
entry_eithout_content.errors
#=> #<Activemodel::Errors:Ox103d3d89188
        @messages=#<0rdredHash {:content=>["can't be blank"]}...>

entry_without_content.errors.each do |attribute, error|
puts "#{attribute} have errors '#{error.to_s}'."
#=> "content have errors 'can't be blank'."
end

entry_without_content.errors.fll-messages
#=> ["Content cat't be blank"]

entry = Entry.new
entry.save
#=> false :バリデーションに失敗しているため保存できない
entry.save :validate => false
#=> true :バリデーションをせずに保存する
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0