0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsで誕生日のサーチ機能を作るときのビュー

Last updated at Posted at 2021-04-04

Railsで誕生日のサーチ機能を作るとき
ただ単にオブジェクトに関連なくparamsを渡して検索結果をとってきたかったのでform_tagを使う。
form_forとかだとオブジェクトと紐づくので今回はform_tag

正直この書き方古いので正しい書き方は下の方に記述。

<%= form_tag({controller: "/members", action: "search",remote:true} ,{method: "get",id: "form1"}) do %>
        <div>
          <p>
            <label class="center-block">名前</label>
          </p>
        </div>
        <p>
          <input class="center-block" type="text" name="name" required="required"><br>
        </p>
        <div>
          <p>
            <label class="center-block">生年月日</label>
          </p>
        </div>
        <div class="center-block text-center">
            <%= select_date(Date.today,:start_year=> 1970,name: 'birth')  %>
        </div>
        <div>
          <p>
            <%= submit_tag '検索する', name: 'public' , class: "center-block" %>
          </p>
        </div>
<% end %>

とした。コントローラー側で

params[:birth] = [params[:date][:year],params[:date][:month],params[:date][:day]].join

としてあとはコントローラ側でゴニョゴニョ使う。
select_dateのタグでサーバに送ったデータは初期値でparams[:date]で取れる。
https://railsguides.jp/form_helpers.html#ベアボーンヘルパー

  def search
    if params[:public]
      params[:birth] = [params[:date][:year],params[:date][:month],params[:date][:day]].join

      @gmaps = Member.includes(:gmaps).where('name = ? AND birth = ? AND magic_word = ?', params[:name], params[:birth],'').references(:gmaps).map(&:gmaps).flatten.uniq
    else
      @gmaps = Gmap.joins(:member).where('magic_word = ? AND magic_word != ? AND email = ?', Digest::MD5.hexdigest(params[:magic_word]), '', params[:email])
    end
    render 'gmaps/index'
  end
<%= form_with url: users_path do |form| %>
 <%= form.date_select :bitrh %>

のように

rails6だと form.date_selectでやっている記事も見るのでとりあえずそっちを使って欲しい。
コントローラ側の処理は参考程度で。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?