2017-07-06 1 views
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.rb

class 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を持っていない工夫を使用していない場合

答えて

0

あなたが考案いるcurrent_userを使用している場合は、単に、

@movie = current_user.movies.create!(movie_params) 

代わりの

@movie = Movie.create!(movie_params) 

行いますログインしたユーザーを取得します(例:@user)。

@movie = @user.movies.create!(movie_params) 
+0

Meh。私はhttps://github.com/lynndylanhurley/devise_token_authを使っていますが、 'current_user'はmovies_controllerで定義されていません。そして、これはログにあります>(未定義メソッド 'movies 'はnil:NilClass): –

+0

@PeterBoomsma次に、2番目のアプローチで述べたようにログインしたユーザーレコードを取得します – Pavan

+0

いいですが、 devise_token_authの宝石でcurrent_user? –

関連する問題