【问题标题】:Create a has_many through record通过记录创建一个 has_many
【发布时间】: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


    【解决方案1】:

    如果你正在使用Devisecurrent_user,那么就这样做

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

    而不是

    @movie = Movie.create!(movie_params)
    

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

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

    【讨论】:

    • 嗯。我正在使用 github.com/lynndylanhurley/devise_token_authcurrent_user 在 movies_controller 中未定义。这是在日志中 > (undefined method movies' for nil:NilClass):`
    • @PeterBoomsma 然后按照我在第二种方法中所说的那样获取登录的用户记录
    • 是的,但我不应该能够将 current_user 与 devise_token_auth gem 一起使用吗?
    • @PeterBoomsma current_user 应该可用。检查用户是否已登录,否则将返回nil
    • 看起来后端验证是......在窗口之外。我已经克隆了示例项目(github.com/neroniaky/angular2-token-example),但也有同样的问题。 Current_user 不可用。所以我想我必须从前端发送用户数据,因为它在那里可用。
    猜你喜欢
    • 2020-11-20
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多