LoginSignup
0
0

More than 5 years have passed since last update.

Ruby on Rails [学習記録-第10章-]

Last updated at Posted at 2019-06-19

アソシエーション

  • アソシエーションとはモデル間の関連付けを管理する機能のことで、定義しておくことでモデルをまたいだデータの呼び出しをより簡単に行うことができる。
  • 今回の場合、UserモデルとAppモデルをアソシエーションで関連付けする。
  • アソシエーションを利用するには以下の2つの条件を満たす必要がある。
    • モデルクラスにhas_manyやbelongs_toなどの定義がされている。
    • 所属する側のテーブルに所属するクラス名_idというカラムがある。
  • Userモデルの視点で考えると、あるuserの作成したappが複数個ある状態と言えます。この状態のことをhas manyの関係といい、今回の場合には「User has many Apps」の状態であると言えます。
  • Userモデルのモデルファイルにhas_many :tweetsと追記する。
user.rb
  class User < ApplicationRecord
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :validatable
    has_many :apps
  end
  • Appモデルの視点で考えると、全てのappはいずれかのuserに属している状態と言えます。
  • この状態のことをbelongs toの関係といい、今回の場合は「App belongs to User」の状態であると言えます。
app.rb
class App < ApplicationRecord
  belongs_to :user
end
  • 以上の作業でアソシエーションが定義できた。
  • さきほど編集を行ったusers_controller.rbのshowアクション部分でのデータの呼び出しにアソシエーションを使用して記述を適用する。
users_controller.rb
class UsersController < ApplicationController

  def show
    @nickname = current_user.nickname
    @apps = current_user.apps.page(params[:page]).per(5).order("created_at DESC")
   #before: @apps = App.where(user_id: current_user.id).page(params[:page]).per(5).order('created_at desc')
  end
  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