LoginSignup
10
15

More than 5 years have passed since last update.

シンプルにBool値を設定できるRailsテクニック

Posted at

#indexの画面で、チェックボックスをポチポチ押す度に、DBを更新して画面がロードされます。複雑なAjax処理ではなく、link_to#updateへのリクエストを発生させ、更新後に#indexにリダイレクトします。

rails_check.gif

モデルの作成

boolean型の属性を持つモデルをscaffoldで作成します。model/view/controllerはscaffoldで作成されたものを元に実装してゆきます。

bundle exec rails g scaffold User name:string admin:boolean

FontAwesome のインストール

チェックボックスは、<input type='checkbox'>ではなく、FontAwesomeのアイコン / を使います。Gemfileに必要なgemを書いて、application.css でロードします。

Gemfile
gem "font-awesome-rails"    
app/assets/stylesheets/application.css
/*
 *= require font-awesome
 */

Railsアプリの編集

viewでは、#indexlink_to でモデルを更新するリンクを配置します。リンク先をuser_path(user, user: {admin: false})、メソッドを method: :put で指定することで、 #update を呼び出して任意の属性を更新できます。

app/views/users/index.html.erb
<table class="table table-striped">
  <% @users.each do |user| %>
    <tr>
      <th><%= user.name %></th>

      <td>
        <% if user.admin %>
          <%= link_to User.human_attribute_name(:admin),
                      user_path(user, user: {admin: false}),
                      method: :put,
                      class: 'fa fa-check-square-o' %>
        <% else %>
          <%= link_to User.human_attribute_name(:admin),
                      user_path(user, user: {admin: true}),
                      method: :put,
                      class: 'fa fa-square-o' %>
        <% end %>
      </td>
    </tr>
  <% end %>
</table>

controllerでは #update が呼び出されると redirect_to#index にリダイレクトさせます。

app/controllers/users_controller.rb
class UsersController < ApplicationController
  # ......
  def update
    if @user.update(user_params)
      redirect_to users_path
    else
      redirect_to users_path, notice: 'Error occurs'
    end
  end
  # ......
end

動作確認

Rails Serverを起動させると、以下のようなチェックボックス状のリンクが表示されます。各チェックボックスをクリックすることで、RailsコンソールでDBが更新されるのが確認できます。

ss.png

turbolinksと組合せると、画面遷移がAjaxで処理されるので、より滑らかに画面が切り替わります。またlink_toをhelperにまとめると、もっと可読性が上がるかもしれません。

10
15
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
10
15