teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

「ユーザーが何も入力しなかった場合」と「該当のユーザーが存在しなかった場合」が逆でしたので編集致しました。

2021/03/09 13:11

投稿

punchan36
punchan36

スコア105

title CHANGED
File without changes
body CHANGED
@@ -25,11 +25,11 @@
25
25
  if params[:name].present? || params[:introduction].present? || params[:sex].present?
26
26
  @users = User.where(['name LIKE ? AND introduction LIKE ? AND sex LIKE ?', "%#{params[:name]}%", "%#{params[:introduction]}%", "#{params[:sex]}%"]).page(params[:page]).per(20)
27
27
  else
28
- # 該当のユーザーが存在しなかった場合。
28
+ # ユーザーが何も入力しなかった場合。
29
29
  @users = User.all.order(created_at: :desc).page(params[:page]).per(20)
30
30
  end
31
31
  if @users == []
32
- # ユーザーが何も入力しなかった場合。
32
+ # 該当のユーザーが存在しなかった場合。
33
33
  @users = User.all.order(created_at: :desc).page(params[:page]).per(20)
34
34
  end
35
35
  end

1

form_withの内容、及びコントローラを追記致しました。

2021/03/09 13:11

投稿

punchan36
punchan36

スコア105

title CHANGED
File without changes
body CHANGED
@@ -5,16 +5,35 @@
5
5
 
6
6
  **users/index.html.erb**
7
7
  ```
8
+ <%= form_with url: users_path, method: :get, local: true do |f| %>
8
- <p>User name</p>
9
+ <p>User name</p>
9
- <%= f.search_field :name, :value => params[:name] %>
10
+ <%= f.search_field :name, :value => params[:name] %>
10
11
 
11
- <p>Keyword</p>
12
+ <p>Keyword</p>
12
- <%= f.search_field :introduction, :value => params[:introduction] %>
13
+ <%= f.search_field :introduction, :value => params[:introduction] %>
13
-
14
+
14
- <p>Gender</p>
15
+ <p>Gender</p>
15
- <%= f.radio_button :sex, "Male", :checked => true if params[:sex]&.include?("Male") %>Male
16
+ <%= f.radio_button :sex, "Male", :checked => true if params[:sex]&.include?("Male") %>Male
16
- <%= f.radio_button :sex, "Female", :checked => true if params[:sex]&.include?("Female") %>Female
17
+ <%= f.radio_button :sex, "Female", :checked => true if params[:sex]&.include?("Female") %>Female
18
+
19
+ <%= f.submit :search, :class => "btn-square-little-rich" %>
20
+ <% end %>
17
21
  ```
22
+ **users_index.html.erb**
23
+ ```
24
+ def index
25
+ if params[:name].present? || params[:introduction].present? || params[:sex].present?
26
+ @users = User.where(['name LIKE ? AND introduction LIKE ? AND sex LIKE ?', "%#{params[:name]}%", "%#{params[:introduction]}%", "#{params[:sex]}%"]).page(params[:page]).per(20)
27
+ else
28
+ # 該当のユーザーが存在しなかった場合。
29
+ @users = User.all.order(created_at: :desc).page(params[:page]).per(20)
30
+ end
31
+ if @users == []
32
+ # ユーザーが何も入力しなかった場合。
33
+ @users = User.all.order(created_at: :desc).page(params[:page]).per(20)
34
+ end
35
+ end
36
+ ```
18
37
 
19
38
  ユーザー名、キーワードの部分は実装出来たのですが、性別のラジオボタンが上手く実装出来ません。
20
39
  `, :checked => true`以降を記述する前は「〇Male 〇Female」の様に表示されていたのですが、if文を付け足す事で「Male Female」の様にラジオボタンの表示自体が消えてしまいました。