suzy1031 / everyday-study-app

0 stars 0 forks source link

[jwt-sessions] UserとStudyのリレーション #26

Closed suzy1031 closed 3 years ago

suzy1031 commented 3 years ago

モデル間のリレーションを設定

# model/study.rb
belong_to :user

# model/user.rb
has_many :studies

current_userを定義

# application_controller.rb

def current_user
@current_user ||= User.find(payload['user_id'])
end

# payloadにはuser_idが内包されている

コントローラーのアクションにcurrent_userを追加

# studies_controller.rb

def index
-studies = Study.this_week_total
+studies = current_user.studies.this_week_total
render json: studies
end

def create
-study = Study.new(study_params)
+study = current_user.studies.build(study_params)
if study.save
render json: study, status: :created
else
render json: erros, status: :unprocessable_entity
end
end