1
1

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 5 years have passed since last update.

条件によりf.radio_buttonにdisabledオプションを付与したい

Posted at

Ruby 2.6.5
Rails 5.2.0
地図上からユーザーの投稿を検索できる機能を持ったアプリを開発しています。

ユーザーがログインしていない時にform_with内の一部のradio_buttonを無効化したかったのですが、
当初は下記のような感じで条件式を書いていました。

index.html.erb

<%= form_with url: map_request_path, method: :get do |f| %>
  <%= f.radio_button :posts, "all_user", checked: true %>全てのユーザーの投稿
  <% if logged_in? %>
    <%= f.radio_button :posts, "following", disabled: false %>自分とフォロー中のユーザーの投稿
    <%= f.radio_button :posts, "current_user", disabled: false %>自分の投稿
  <% else %>
    <%= f.radio_button :posts, "following", disabled: true %>自分とフォロー中のユーザーの投稿
    <%= f.radio_button :posts, "current_user", disabled: true %>自分の投稿
  <% end %>
  <%= f.submit '投稿されたお店を表示', class: "btn btn-primary" %>
<% end %>

<div id="map_index"></div>
<script>
  ~
  ~
  ~
  initMap();
</script>

if logged_in? で 条件により disabled: の箇所を操作していたのですが、冗長なコードとなっていました。
一行でどうにかしたかったので調べてみた結果、下記のようにすることでスッキリしました。

index.html.erb

<%= form_with url: map_request_path, method: :get do |f| %>
  <%= f.radio_button :posts, "all_user", checked: true %>全てのユーザーの投稿
  <%= f.radio_button :posts, "following", disabled: current_user.nil? %>自分とフォロー中のユーザーの投稿
  <%= f.radio_button :posts, "current_user", disabled: current_user.nil? %>自分の投稿
  <%= f.submit '投稿されたお店を表示', class: "btn btn-primary" %>
<% end %>

<div id="map_index"></div>
<script>
  ~
  ~
  ~
  initMap();
</script>

disabled: current_user.nil? と書き、
current_user が空かどうか (ログインしているかどうか)の真偽値を disabled: の箇所に持ってくることができました。

ログインしていない時
スクリーンショット 2020-09-20 17.07.05.jpg

ログインしている時
スクリーンショット 2020-09-20 17.07.22.jpg

参考にさせていただきました

条件によりtext_fieldにreadonlyオプションを付与したい

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?