Активная запись: идентификатор_пользователя не назначается во вложенных отношениях - PullRequest
0 голосов
/ 08 ноября 2019

Я вложил отношения и построил их в соответствии с Rails Guide . A User имеет множество Collections, в которых много Sections, каждый из которых содержит множество Links. Однако при создании нового Link user_id не присваивается, а всегда nil. section_id и collection_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, 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

Ссылка

class Link < ApplicationRecord
  belongs_to :section
end

Это правильный способ установить отношения, и может ли кто-нибудь помочь мне понять, что мне не хватает?

1 Ответ

2 голосов
/ 08 ноября 2019

Вы не можете сделать

@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

Но, как отмечает Эндрю Шварц в комментариях, добавление поля user_id в таблицу links могло быть ошибкой конструкции. У вас есть User модель has_many :links, through: :sections, dependent: :destroy, которая не использует никакого поля user_id в записи ссылки. Он использует поле user_id в таблице collections

Простое добавление user_id к таблице links НЕ будет означать, что ссылка будет возвращена, когда вы выполните my_user.links ... она выиграла 't be.

Поскольку вы передаете 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 получить пользователя ссылки.

...