0
Rubyプロジェクトには映画とウォッチリストモデルがあります。レコードを使ってhas_manyを作成する
class Movie < ApplicationRecord
has_many :watchlists
has_many :users, through: :watchlists
end
user.rb
class User < ActiveRecord::Base
has_many :watchlists
has_many :movies, through: :watchlists
# Include default devise modules.
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:trackable,
:validatable,
# :confirmable,
:omniauthable
include DeviseTokenAuth::Concerns::User
end
watchlist.rb
class Watchlist < ApplicationRecord
belongs_to :movie
belongs_to :user
end
そして、これはMoviesControllerです::
movie.rbclass MoviesController < ApplicationController
before_action :set_movie, only: [:show, :update, :destroy]
# POST /movies
def create
if Movie.exists?(title: movie_params[:title])
render json: { body: 'Movie already exists', status: 400 }
else
@movie = Movie.create!(movie_params)
render json: { body: @movie, status: 200 }
end
end
def movie_params
# whitelist params
params.permit(:title, :created_by, :id)
end
end
現在、ムービーはムービーテーブルにのみ保存されています。ウォッチリストにムービーIDとユーザーIDを持つレコードを作成するにはどうすればよいですか?あなたはを使用していない場合current_user
を持っていない工夫
Meh。私はhttps://github.com/lynndylanhurley/devise_token_authを使っていますが、 'current_user'はmovies_controllerで定義されていません。そして、これはログにあります>(未定義メソッド 'movies 'はnil:NilClass): –
@PeterBoomsma次に、2番目のアプローチで述べたようにログインしたユーザーレコードを取得します – Pavan
いいですが、 devise_token_authの宝石でcurrent_user? –