条件によりf.radio_buttonにdisabledオプションを付与したい
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: の箇所に持ってくることができました。
参考にさせていただきました
Author And Source
この問題について(条件によりf.radio_buttonにdisabledオプションを付与したい), 我々は、より多くの情報をここで見つけました https://qiita.com/nideratakumin/items/aa8689810803acd57a1d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .