LoginSignup
0
3

More than 3 years have passed since last update.

whereメソッドと正規表現で別テーブルの存在確認

Last updated at Posted at 2020-03-25

概要

模擬フリマアプリ作成時、
別テーブルに該当のIDをもつレコードが存在するか確認し、存在すればテキストを表示させるところでかなり詰まったので備忘録としてまとめます。

具体的には商品(Product)がPay.jpを通して決済がおきた時に、取り引き(Transaction)テーブルにproduct_idが保存される形となっています。

トップページでは商品をancestryを使ってカテゴリー別に一覧表示させており、商品が既に取り引き済だった場合に、「SOLD OUT」の文字を表示させます。

完成イメージ

Image from Gyazo

各テーブル

class CreateProducts < ActiveRecord::Migration[5.2]
  def change
    create_table :products do |t|
      t.string :name, null: false
      t.integer :price, null: false
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end
class CreateTransactions < ActiveRecord::Migration[5.2]
  def change
    create_table :transactions do |t|
      t.references :product, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end

コントローラー

class ProductsController < ApplicationController
  def index
    # カテゴリー別 一覧表示
    # アンセストリーのID毎に10件ずつ商品を取得
    @ladies_products = Product.where(category_id: 20..85).limit(10)
    @mens_products = Product.where(category_id: 91..144).limit(10)
    @appliances_products = Product.where(category_id: 408..434).limit(10)

    # カテゴリー別 Sold Out Check
    # idsと複数形になるところを気付くのにも時間がかかりました
    @ladies_transaction = Transaction.where(product_id: @ladies_products.ids)
    @mens_transaction = Transaction.where(product_id: @mens_products.ids)
    @appliances_transaction = Transaction.where(product_id: @appliances_products.ids)
  end
end

ビュー

    .top__genre-items
      - @ladies_products.each do |product|
        .top__genre-item
          = link_to product_path(product.id), class:"top__genre-item-link" do
            .top__genre-item-pict
              = image_tag product.images.first.image.url, alt:"商品画像", class: "top__genre-item-img"
            .top__genre-body
              .top__genre-body-price
                .top__genre-body-price--yen
                  ¥
                .top__genre-body-price--value
                  = product.price
              .top__genre-body-name
                = product.name
              -# Sold Out Check
              -# @*****_transactionに値が入っているか確認
              - if @ladies_transaction.present?
              -# @*****_transactionの配列に入っている一番最初の要素のproduct_idとeachで表示させているProductのIDが適合すればSOLD OUTを表示
                - if @ladies_transaction.first.product_id == product.id
                  .top__transaction-check
                    .top__transaction-check--btn
                      SOLD OUT

firstが肝でしたね・・・!
精進します・・・!

以上となります

もっといい方法があればご教示くださいm(__)m

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