ihatov08 blog

プログラミング初心者だけどRailsとSwiftマスターします

modelで次、前ボタンの実装方法

単純に考えると、id+1もしくはid-1で実装できる。

class Video < ActiveRecord::Base
    def next
        Video.find(id+1)
    end
    def prev
        Video.find(id-1)
    end
end

しかし、この実装方法だと問題が生じる。 idが1,2,3,4,5,6が存在して、途中で例えばid=4を削除したときにidが存在しなくなってしまう。 以下の実装に変更する。

class Hoge < ActiveRecord::Base
    def next
        Hoge.where("id > ?", id).first
    end
    def prev
        Hoge.where("id < ?", id).last
    end
end

controllerの実装方法。主にはshowアクションに定義することになると思う。

  def show
    @hoges = Video.all

    @next_hoge = @hoge.next
    @prev_hoge = @hoge.prev
  end

showページの実装 次のidもしくは前のidが存在する場合のみ、リンクボタンを表示させている。 たとえばhoge id=1の場合は、

          <div class="card-action">
              <%= link_to "Previous", @prev_hoge if !@prev_hoge.nil? %>
              <span class="right">
                  <%= link_to "Next", @next_hoge if !@next_hoge.nil? %>
              </span>