创建has_many通过记录



我的Ruby项目中有一个用户看电影和一个监视列表模型。

电影.rb:

class Movie < ApplicationRecord
has_many :watchlists
has_many :users, through: :watchlists
end

用户.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

监视列表.rb

class Watchlist < ApplicationRecord
belongs_to :movie
belongs_to :user
end

这是电影控制器:

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 的记录?

如果你正在使用Devisecurrent_user,只需

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

而不是

@movie = Movie.create!(movie_params)

如果您不使用Devise没有current_user,请获取登录用户,说@user并执行

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

最新更新