LoginSignup
0
0

More than 3 years have passed since last update.

rails 発展その4 アソシエーション

Last updated at Posted at 2019-11-08

モデルを跨いだデータの呼び出しができるようになります。

ユーザー情報と商品情報などは別テーブルで保存されてることがあり
簡単なコードで呼び出せるようにするコードのこと

app/models/user.rb
  class User < ApplicationRecord 
    has_many :items
  end
  # ユーザーにたいし複数のアイテムがある時などは has_manyで定義
app/models/item.rb
  class Item < ApplicationRecord 
    belongs_to :user
  end
  # こちらは逆にアイテムにたいしユーザーは一人だけなのでbelongs_toと定義

htmlやコントローラーでの使用の場合は

controller
    def show 
      @items = current_user.items
      #これでユーザーからアイテムの情報を全て持ってきます。
      @item = current_user.items[0]
     #上記に続いて特定のidの情報だけ取り出します。
      @user = item.current_user
      #belongs_toと定義されてるのでこれだけでユーザー情報を持ってきます。 
    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