3
1

More than 1 year has passed since last update.

view内でif文を用いた条件分岐のスマートな書き方[Ruby, Rails]

Posted at

はじめに

今回の記事はとても局所的なテーマを扱います

Rubyの構文において、以下のようなif文を用いた冗長的な書き方を、よりスマートにまとめます

app/views/announcement.html.erb

Before
<th>配信元</th>
<td>
    <% if @announcement.user_id %>
        <%= @announcement.user.name %>
    <% else %>
        管理者
    <% end %>
</td>

結論

三項演算子を用いて、かつ文字列の部分はStringオブジェクトにします

After
<th>配信元</th>
<td><%= @announcement.user_id ? @announcement.user.name : "管理者" %></td>

想定状況

announcementインスタンスはuserインスタンスに紐づく、もしくは紐づいていない、状況です

app/models/user.rb
class User < ApplicationRecord
  has_many :announcements, dependent: :destroy
end
app/models/announcement.rb
class Announcement < ApplicationRecord
  belongs_to :client, optional: true
end

ポイント

文字列の部分をStringクラスにしていること

以下の場合、Encountered a syntax error while rendering templateのエラーが発生し、失敗します。理由は、Railsが<%= %>のなかに、存在しない変数もしくはメソッドを探してしまうからです(管理者の部分)。

なので、ただの文字列の場合でもクオテーションで囲んであげることで、ただの文字列を文字列オブジェクトにする必要があります。

失敗例
<th>配信元</th>
<td><%= @announcement.user_id ? @announcement.user.name : 管理者 %></td>
# 管理者 → "管理者" こうしないとだめ

さいごに

とても小さなテーマですが、5行が1行になったことは感動しました(知識不足なだけやん

最後までお読み頂きありがとうございました!

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