LoginSignup
1
0

More than 5 years have passed since last update.

モデルにロジックを書いてみる

Posted at

 やはり、モデルにロジックを書くことがプログラミングの醍醐味ではないかな、と思います。
今回は、コントローラに書いた記述をモデルにロジックとして移行してみます!

controllerの記述

  • 実装内容
    テーブルのデータを降順、昇順にする

  • コード

texts_contoroller.rb
class TextsController < ApplicationController

    def index
       if request.fullpath.include?('desc')
           @texts = Text.all.desc_sort
           @sort = "asc"
       else
           @texts = Text.all.asc_sort
           @sort = "desc"
       end
    end
end
text.rb
class Text < ApplicationRecord

    scope :asc_sort, ->{ order(id: :asc)}
    scope :desc_sort, ->{ order(id: :desc)}
end
index.html.erb
<%= link_to 'スキル', texts_path(id: @sort) %>

上記の記述の説明は一つ前の記事に掲載しています。

モデルにてロジックを書く

それでは、早速上記のコントローラをロジックに移行していきましょう。

まず、目指すべきなのは上記の実装をメソッド化することです。
そうすれば、子クラスで同一の実装をするときにすぐに呼び出せますよね。

私はこのように書きました。

texts_controller.rb
class TextsController < ApplicationController

    def index
        path_desc = request.fullpath.include?('desc')
        @texts = Text.data_sort(path_desc)
        @sort = Text.sort_key(path_desc)
    end

end
text.rb
class Text < ApplicationRecord

    scope :asc_sort, ->{ order(id: :asc)}
    scope :desc_sort, ->{ order(id: :desc)}

    def self.data_sort(path)
        if path
            Text.all.desc_sort
        else
            Text.all.asc_sort
        end
    end

    def self.sort_key(path)
        if path
            "asc"
        else
            "desc"
        end
    end

end
  • メソッドの引数にpathを設定
  • メソッド内でpathによる条件分岐→pathにパラメータを割り振っている状態
  • 1番目のメソッドで実際に昇順、降順の並び替えを実施
  • 2番目のメソッドはpathへのパラメータを割り振る用のメソッド、文字列をstringsクラスにすることを忘れない

これからもどんどんロジック書いていきます!

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