【发布时间】:2017-07-06 19:56:02
【问题描述】:
我的 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
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 的记录?
【问题讨论】:
标签: ruby-on-rails model-associations