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

データベースにデータのあるなしで分岐

Last updated at Posted at 2021-04-18

先ほど閃きました。

Q:itemsテーブルにデータがあるかないかで分岐させる条件は?

A:id番号1のデータがあるかないかを検索すること(これは△)

なので

Viewには以下のように記述しました。

<% if Item.exists?(1) %>
<% else %>
<% end %>

(参考)メソッドの簡単解説

メソッド名 働き 戻り値の型
exists? 指定した条件のレコードがデータベースに存在するか 真偽値で返す
オブジェクト.exists?(条件)

参考:【Rails】exists?メソッドの使い方(基礎~応用編,present?との違い)

https://pikawaka.com/rails/exists

A:id番号データがあるかないかを検索すること(これは◎)

もっと簡単な方法は

<% if Item.exists?%>
<% else %>
<% end %>

(1)もかかない
⇨というのも今はデータ1があるこご前提だが、全てデータを行削除して続けると
続きの番号しか取らないので1は永遠に存在しなくなり、データが溜まってもデータなしの状態で表示を続けるため。

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?