活动记录:未以嵌套关系分配User_id

我有嵌套关系,并根据Rails Guide建立了它们。 User有许多Collections,其中有许多Sections,每个都包含许多Links。但是,在创建新的Link时,user_id未被分配,但始终为nilsection_idcollection_id的设置正确。

控制器

class Api::V1::LinksController < Api::V1::BaseController
  acts_as_token_authentication_handler_for User,only: [:create]

  def create
    @link = Link.new(link_params)
    @link.user_id = current_user
    authorize @link
    if @link.save
      render :show,status: :created
    else
      render_error
    end
  end

  private

  def link_params
    params.require(:resource).permit(:title,:description,:category,:image,:type,:url,:collection_id,:user_id,:section_id)
  end

  def render_error
    render json: { errors: @resource.errors.full_messages },status: :unprocessable_entity
  end
end

模型

用户

class User < ApplicationRecord
  devise :database_authenticatable,:registerable,:recoverable,:rememberable,:validatable
  acts_as_token_authenticatable
  has_many :collections,dependent: :destroy
  has_many :sections,through: :collections,dependent: :destroy
  has_many :links,through: :sections,dependent: :destroy

  mount_uploader :image,PhotoUploader
end

收藏

class Collection < ApplicationRecord
  belongs_to :user
  has_many :sections,PhotoUploader
end

部分

class Section < ApplicationRecord
  belongs_to :collection
  has_many :links,dependent: :destroy
end

链接

class Link < ApplicationRecord
  belongs_to :section
end

这是建立关系的正确方法,有人可以帮助我了解我所缺少的吗?

brittany1988 回答:活动记录:未以嵌套关系分配User_id

你不能做

@link.user_id = current_user

您可以(代替)做...

@link.user_id = current_user.id

或更优雅...

@link.user = current_user

假设您将在模型中定义关系

class Link < ApplicationRecord
  belongs_to :section
  belongs_to :user
end

但是正如Andrew Schwartz在评论中指出的那样,将字段user_id添加到links表中可能是设计错误。在User模型has_many :links,through: :sections,dependent: :destroy中,您没有使用链接记录中的任何user_id字段。它使用user_id

中的collections字段

仅将user_id添加到links表中并不意味着当您执行my_user.links时链接将被返回……不会。

由于您在section_id中传递了一个link_params,足以创建到用户的链接,因此只需编写迁移操作以删除user_id字段即可。如果您希望能够从链接中看到关联的用户,请执行...

class Link < ApplicationRecord
  belongs_to :section
  has_one :collection,through: :section
  has_one :user,through: :collection
end

,这将使您执行my_link.user来检索链接的用户。

本文链接:https://www.f2er.com/3138370.html

大家都在问