LoginSignup
0
0

More than 3 years have passed since last update.

Rails 備忘録

Posted at

validates
onとif
on: バリデーションの実行タイミング

class Person < ApplicationRecord
  # 値が重複していてもemailを更新できる
  validates :email, uniqueness: true, on: :create

  # 新規レコード作成時に、数字でない年齢表現を使える
  validates :age, numericality: true, on: :update

  # デフォルト (作成時と更新時の両方でバリデーションを行なう)
  validates :name, presence: true
end

if: バリデーションを行う条件

class Order < ApplicationRecord
  validates :card_number, presence: true, if: :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end

両方シンボルで指定することに注意

nil?
nilだけtrue

empty?
空文字、空配列true

blank
両方

ランダム数値

format("%0#{n}d", SecureRandom.random_number(10**n))

memberとcollectionの違い
簡単に言うと、routingにidが付くか付かないか

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