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が付くか付かないか