LoginSignup
1
0

More than 3 years have passed since last update.

hidden_field_tagの使い方

Posted at

はじめに

Railsアプリ作成時にhidden_field_tagを使ったので、その時の内容のメモ書きになります。
検索機能を使った時にパラメータが飛ばなかったのでhidden_field_tagを使用し対応した時の内容になります^^

使用方法

hidden_fieldhidden_field_tagは用途は似ているが使い方が違う。
hidden_fieldform_forform_withの中で使用するに対し、

hidden_field_tagは一つだけで使用でき単体でパラメーターを渡したいときに使用する。
form_for内でも使用はできます。

作業内容

このように検索窓のソースがあります。

app/views/texts/index.html.erb
<%= search_form_for @eq do |f| %>
      <div class="d-flex">
        <div class="form-group flex-grow-1">
          <%= f.search_field :title_cont, placeholder: "教材を探す", class: "form-control" %>
        </div>
        <div> 
        <%= f.submit "検索", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

viewの表示はこのようにコントローラーで指示をしています。

app/controllers/texts_controller.rb
def index
    if params[:genre].nil? 
      @eq = Text.where(genre: ["Ruby on Rails", "Git","Basic","Ruby"]).ransack(params[:q])
    else
      @eq = Text.where(genre: params[:genre]).ransack(params[:q])
    end
      @texts = @eq.result.order(:id)
  end

そこで
indexアクションに記述してある
if params[:genre].nil?はパラメータが空ならtureで以下実行するという記述です。

一部ページのパスにgenre:を埋め込んでいます。

<%= link_to " Ruby/Rails教材", texts_path, class: "dropdown-item" %>
<%= link_to "動画教材", movies_path, class: "dropdown-item" %>
<%= link_to "PHP教材", texts_path(genre: "PHP"), class: "dropdown-item" %>
<%= link_to "プログラミング勉強会", movies_path(genre: "Live"), class: "dropdown-item" %>
<%= link_to "質問集", questions_path, class: "dropdown-item" %>
.
.
.
.

表示するページ事に[:genre]を付けて色分けしています。
なのでリンクからの表示なら問題は無いのです。

が、

今回は検索して表示が目的なので、

このままだと
キーワード検索してもgenreのparamsに値が無いのでtrueで表示されます。

app/views/texts/index.html.erb
<%= f.search_field :title_cont, placeholder: "教材を探す", class: "form-control" %>

↑今のままだと検索かけたとしてもユーザーが記入した文字列しか飛ばしていません。

ターミナル
           部分一致検索→"p"→検索
 Parameters: {"q"=>{"title_cont"=>"p"}, "commit"=>"検索"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 3], ["LIMIT", 1]]

From: /Users/ikedakeigo/Desktop/gyakuten_clone_group27/app/controllers/texts_controller.rb:4 TextsController#index:

     2: def index
     3:   binding.pry
 =>  4:   if params[:genre].nil? 
     5:     @eq = Text.where(genre: ["Ruby on Rails", "Git","Basic","Ruby"]).ransack(params[:q])
     6:   else
     7:     @eq = Text.where(genre: params[:genre]).ransack(params[:q])
     8:   end
     9:     @texts = @eq.result.order(:id)
    10: end

[1] pry(#<TextsController>)> params[:genre]
=> nil ⇦:genreに値が入っていない。

そこでhiddenfield_tagの出番です!
:genreを単体で送り込みましょう。

app/views/texts/index.html.erb
  <%= search_form_for @eq do |f| %>
      <div class="d-flex">
        <div class="form-group flex-grow-1">
          <%= f.search_field :title_cont, placeholder: "教材を探す", class: "form-control" %>
        </div>
        <div> 
        <%= hidden_field_tag(:genre, "Php")%> ⇦追加
        <%= f.submit "検索", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

このように記述すると検索キーワードと:genreを飛ばすことができます!
が、
このままだと常に中身がPhpfalseが返され特定の物しか検索できない形になります。

そこで条件分岐を付けて上げて柔軟に対応するようにします。

app/views/texts/index.html.erb
  <%= search_form_for @eq do |f| %>
      <div class="d-flex">
        <div class="form-group flex-grow-1">
          <%= f.search_field :title_cont, placeholder: "教材を探す", class: "form-control" %>
        </div>
        <div>               
        <%= hidden_field_tag(:genre, params[:genre]) if params[:genre].present? %> ⇦追加
        <%= f.submit "検索", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

present?メソッドは 「〜が存在するとき」の条件分岐

表示しているページによって:genreに値を付けているので、
それで判断させています。

これでページ事のキーワード検索ができました!^^

おわりに

コード書いていると極々普通なことかもしれませんが、
悩んでいたことが、上手くできると
「ん?いや、普通に考えたらわかるやん!」っておわりに気づくことがあります^^笑

なんでも諦めないことですね!^^

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