1
1

More than 3 years have passed since last update.

before_actionの使い方

Posted at

プログラミングスクールの最終課題フリマアプリの開発において
コードレビューの際に指摘をもらった箇所を復習用に記録しておきます。

マイページ実装の際にrailsでcredit_card_controller.rbに
コードを記載しました。
重複しているコードを別で定義して書き変え、before_actionにて呼び出すようにとのこと。

@card = CreditCard.find_by(user_id: current_user.id)

このコードを下記のように定義し、before_actionで呼び出しました。

  def find_card
    @card = CreditCard.find_by(user_id: current_user.id)
  end

今回はcreate意外でbefore_actionが実行されれば良いので
下記のようにnew,show,destroyと指定しております。

class CreditCardsController < ApplicationController
  require "payjp" 
  before_action :find_card, only:[:new, :show, :destroy]

コードを書く際には、重複するコードは極力まとめることが
スッキリしたコードを書くポイントのようなので
次回以降の実装においても、このポイントを意識して行います。

1
1
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
1
1