3
3

More than 3 years have passed since last update.

[memo]Railsのpresent?メソッドの使い方

Last updated at Posted at 2021-01-24

present?メソッドとは

オブジェクトであるレシーバーの値が存在すればtrue、存在しなければfalseを返すメソッドです。条件分岐(if文等)をプログラムで書くときによく使います。

例えばアプリの購入機能において「もし選択した商品に紐づく購入記録が存在していたら(空ではなかったら)、"sold out"と表示する」を実装したい場合は該当のビューファイルにおいて

index.html.erb

<% if item.purchase.present? %>
<div class='sold-out'>
<span>Sold Out!!</span>
</div>
<% end %>

という様に記述します。

<% if item.purchase.present? %>の部分ですが
itemモデルとpurchaseモデルにテーブル間のアソシエーションが組んであれば
商品(item)に紐づく購入記録(purchase)が存在していたら(空ではなかったら)=true
という解釈になります。

以下のサイトにはpresent?メソッドと逆のblank?メソッドも紹介されています。

参考:https://techacademy.jp/magazine/20214

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