LoginSignup
0
0

More than 3 years have passed since last update.

アソシエーションを用いたデータ読み込み削減

Posted at

はじめに

この投稿はRailsで開発しているフリーマーケット機能を持ったWEBアプリケーションで、データのやり取り回数を削減できることをメモしておくものです。

前提

Ruby 2.6.5p114
Rails 6.0.3.4
macOS Catalina

アソシエーション

app/models/item.rb
  belongs_to :user
  has_one :order
app/models/order.rb
  belongs_to :user
  belongs_to :item
app/models/user.rb
  has_many :items
  has_many :orders

itemと紐づけられたuserの情報を読み込む方法

商品詳細が表示される際に、ログインしているユーザーと出品しているユーザーが、同一人物の場合と同一人物ではない場合で条件分岐処理を行う必要がありました。前者の分岐処理の記述では余分なデータの読み込みが発生してしまいます。
後者の記述ではアソシエーションを活用した読み込みの手間の少ない可読性の高い記述となっています。

app/views/items/show.html.erb
   <% if Order.find_by(item_id: @item.id) == nil %>
      <% if user_signed_in? && current_user.id == @item.user.id %>
        <中略>
      <% elsif user_signed_in? %>
        <中略>
      <% end %>
    <% end %>
app/views/items/show.html.erb
    <% if @item.order == nil %>
      <% if user_signed_in? && current_user.id == @item.user.id %>
        <中略>
      <% elsif user_signed_in? %>
        <中略>
      <% end %>
    <% end %>
0
0
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
0