前書き
これは記事というより個人的な忘却録として残します。
指摘箇所
⇨find_or_create_by()メソッドを使おう
モデル.find_or_create_by(引数). ⇨引数の条件でモデルからレコードを探しあれば戻り値として返すが、見つからない場合は(引数)をモデルに新規作成する。
私のコード. ↓では
def set_customer @customer = Customer.find_by(id: cookies.signed[:customer_id]) return unless @customer.nil? @customer = Customer.create cookies.permanent.signed[:customer_id] = @customer.id end
ファクタリング後
def set_customer @customer = Customer.find_or_create_by(id: cookies.signed[:customer_id]) cookies.permanent.signed[:customer_id] = @customer.id if @customer.id.nil? end