rails "before_action"で記述を簡素化しよう!
Hey, guys!
railsでコードを書いていて同じコードが重複してしまうことってあるよね??
なるべく重複したコードは避けたい。。
そんな時に使えるbefore_actionで簡素化してみよう!
よくある重複する例としては
@article = Article.find(params[:id])
findを使って記事をArticleモデルのデータベースから取り出してくる時。
def show @article = Article.find(params[:id]) end def edit @article = Article.find(params[:id]) end def update @article = Article.find(params[:id]) end def destroy @article = Article.find(params[:id]) end
4つのアクション内で同じものが重複してしまっている...
そんな時に使えるのがbefore_actionだ。
とりあえずコードの一番下に重複した部分をメソッドとして追加してみる。
def set_article @article = Article.find(params[:id]) end
これを記述した後にbefore_actionを同ファイルの上の方に記述。
set_articleメソッドを記述すること。
before_action :set_article
これでOK! それでは重複した部分を削除しよう!
before_action :set_article def show end def edit end def update end def destroy end def set_article @article = Article.find(params[:id]) end
こうするとshowアクションとかが実行される前にset_articleアクションが読み込まれる。
また、onlyでアクションを指定することも出来る!
before_action :set_article, only:[:show, :edit, :update, :destroy]
簡単でしょ?
Have a wonderful Christmas!
My boss, technuma san, advised me how to spend the Christmas in best way.
"Just write codes ;)"
See you :)