2017-07-06 135 views
0

我在我的Ruby項目中有一個用戶電影和監視列表模型。通過記錄創建has_many

movie.rb:

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:

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的記錄?

回答

0

如果使用設計已經current_user,只是做

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

,而不是

@movie = Movie.create!(movie_params) 

如果不使用設計沒有current_user,獲取登錄的用戶,例如@user並執行

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

呃。我使用的是https://github.com/lynndylanhurley/devise_token_auth,但'current_user'在movies_controller中未定義。這是在日誌>'(未定義的方法'電影爲零:NilClass):' –

+0

@PeterBoomsma然後獲取登錄的用戶記錄,如我在第二種方法 – Pavan

+0

是的好吧,但我不應該能夠使用具有devise_token_auth gem的current_user? –

相關問題