LoginSignup
2
0

More than 3 years have passed since last update.

Rails「paramsの使用法」

Last updated at Posted at 2021-02-26

はじめに

今回、テキストの一覧ページを作成する際、link_toとhelperよりparamsの使用方法を復習できたので共有します。

やりたいこと

・viewで各教材の一覧ページへのリンクを設定する
・controllerで各教材の一覧ページに適した教材を取得する
・helperで一覧ページのタイトルを表示する処理を書く

viewで各教材の一覧ページへのリンクを設定する

_header.html.erb
<%= link_to "Ruby/Rails教材", texts_path, class: "dropdown-item" %>
<%= link_to "AWS講座", texts_path(genre: "AWS"), class: "dropdown-item" %>
<%= link_to "PHPテキスト教材", texts_path(genre: "Php"), class: "dropdown-item" %>

<%= link_to "表示名",次のアクションへ遷移するパス(パラメーター),class: "クラス名" %>
となるよう記述します。

各教材の一覧ページへのパスtext_pathにパラメーターとしてgenreを指定することで、表示する教材を制限します。

controllerに条件分岐を記述

texts_controller.rb
  def index
    if params[:genre] == nil
      @texts = Text.where(genre: ["Basic", "Git", "Ruby", "Ruby on Rails"])
    else
      @texts = Text.where(genre: params[:genre])
    end
  end

パラメーターgenreの指定がない場合とある場合で条件分岐し、条件にあった教材だけ取得するようにします。

helperに変換部分を作り教材毎にページタイトルが変わるようにする

texts_helper.rb
module TextsHelper
  def page_title
    if params[:genre] == nil
      "Ruby/Rails"
    else
      params[:genre]
    end
  end
end

helperにpage_titleというメソッドを定義し、パラメーターgenreの指定がない場合はRuby/Railsを表示し、指定がある場合はその教材のgenre名を表示するよう処理を書きます。

helperは、定義しておくことでview内でその処理を呼び出すことができ、viewをよりシンプルに書くことができます。

一覧ページのview

index.html.erb
<div class="text-title">
  <h3><%= page_title %>テキスト教材</h3>
</div>

<% @texts.each do |text| %>
  <div class="card-body">
   <p class="card-text"><%= text.title %></p>
   <p class="card-text"><%= text.genre %></p>
  </div>
<% end %>

viewで <%= page_title(helperで定義したメソッド) %> を記述し、ページ毎にタイトルを表示するようにします。

controllerで定義した@textsはeachの繰り返し処理でtitleとgenreを表示するようにします。

まとめ

このようにcontrollerとhelperでパラメーターを元に条件分岐することで、一覧ページごとに適したタイトルとテキストを表示することができました。

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