[RUBY] How to use hidden_field_tag

Introduction

Since I used hidden_field_tag when creating the Rails application, it will be a memo of the contents at that time. Since the parameter did not skip when using the search function, it will be the content when corresponding using hidden_field_tag ^ ^

how to use

hidden_field and hidden_field_tag have similar uses but different uses. Whereas hidden_field is used in form_for and form_with,

You can use only one hidden_field_tag, and use it when you want to pass parameters by itself. It can also be used in form_for`.

Work content

There is a search window source like this.

: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: "Find teaching materials", class: "form-control" %>
        </div>
        <div> 
        <%= f.submit "Search", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

The display of view is instructed by the controller like this.

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

Therefore Described in the index action if params [: genre] .nil? is a description that if the parameter is empty, ture will execute the following.

I have embedded genre: in the path of some pages.

<%= link_to " Ruby/Rails teaching materials", texts_path, class: "dropdown-item" %>
<%= link_to "Video teaching materials", movies_path, class: "dropdown-item" %>
<%= link_to "PHP teaching materials", texts_path(genre: "PHP"), class: "dropdown-item" %>
<%= link_to "Programming study session", movies_path(genre: "Live"), class: "dropdown-item" %>
<%= link_to "Question collection", questions_path, class: "dropdown-item" %>
.
.
.
.

The pages to be displayed are color-coded with [: genre]. So there is no problem if it is displayed from the link.

But,

This time, the purpose is search and display, so

At this rate Even if you search by keyword, there is no value in paramsofgenre, so it is displayed as true.

:app/views/texts/index.html.erb


<%= f.search_field :title_cont, placeholder: "Find teaching materials", class: "form-control" %>

↑ Even if you search for it as it is, only the character string entered by the user is skipped.

Terminal


Partial match search →"p"→ Search
 Parameters: {"q"=>{"title_cont"=>"p"}, "commit"=>"Search"}
  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 ⇦:There is no value in genre.

That's where hiddenfield_tag comes in! Let's send: genre alone.

: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: "Find teaching materials", class: "form-control" %>
        </div>
        <div> 
        <%= hidden_field_tag(:genre, "Php")%>⇦ Add
        <%= f.submit "Search", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

If you write it like this, you can skip the search keyword and: genre! But, If this is left as it is, the contents will always be Php and false will be returned, and only specific items can be searched.

Therefore, add a conditional branch to increase it flexibly.

: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: "Find teaching materials", class: "form-control" %>
        </div>
        <div>               
        <%= hidden_field_tag(:genre, params[:genre]) if params[:genre].present? %>⇦ Add
        <%= f.submit "Search", class: "btn btn-primary ml-1" %>
        </div>
      </div>
    <% end %>

The present? method is a conditional branch of " when "is present"

Since : genre is priced according to the page you are viewing, That's how I make the decision.

Now you can search the page by keyword! ^^

in conclusion

It may be quite normal to write code, but If you can do what you were worried about You may notice the end, "Hmm? No, you can understand it if you think about it normally!" ^^ lol

Don't give up on anything! ^^

Recommended Posts

How to use hidden_field_tag
How to use Map
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
How to use Big Decimal
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use Java variables
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer
[Java] How to use Optional ①
How to use Lombok now
[Creating] How to use JUnit
[Rails] How to use Scope
How to use the link_to method
How to use arrays (personal memorandum)
How to use scope (JSP & Servlet)
How to use the include? method
[Rails] How to use devise (Note)
How to use the form_with method
How to use EventBus3 and ThreadMode
How to use Spring Data JDBC
How to use binding.pry [53 days left]
How to use Java HttpClient (Post)