创建has_many到记录

时间:2017-07-06 19:56:02

标签: ruby-on-rails model-associations

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

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

1 个答案:

答案 0 :(得分:0)

如果你使用 Devise current_user,那就去做

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

而不是

@movie = Movie.create!(movie_params)

如果未使用设计 但没有current_user,请抓取登录用户,说@user并执行

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