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

Active Record: User_id not being assigned in nested relationship

我有嵌套关系并根据 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

Collection

class Collection < ApplicationRecord
  belongs_to :user
  has_many :sections, dependent: :destroy
  has_many :links, through: :sections, dependent: :destroy

  mount_uploader :image, PhotoUploader
end

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

Link

class Link < ApplicationRecord
  belongs_to :section
end

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

你做不到

@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 table 可能是一个设计错误。您在 User 模型 has_many :links, through: :sections, dependent: :destroy 中没有使用 link 记录中的任何 user_id 字段。它使用 collections table

中的 user_id 字段

只需将 user_id 添加到 links table 并不意味着当您执行 my_user.links 时将返回 link ... 它不会'不会。

由于您在 link_params 中传递 section_id 足以为用户创建 link,因此只需编写迁移以删除 user_id 场地。如果您希望能够看到来自 link 的关联用户,请执行...

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

这将使您可以 my_link.user 检索 link 的用户。