«ОШИБКА: двойное значение ключа нарушает уникальное ограничение» has_many - PullRequest
0 голосов
/ 05 марта 2020

У меня есть has_many через настройку связи между моделью пользователя и моделью библиотеки. Модель пользователя:

class User < ApplicationRecord

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_one :library, dependent: :destroy
  has_many :articles, through: :library

end

Модель статьи:

class Article < ApplicationRecord
  geocoded_by :address
  after_validation :geocode, if: :will_save_change_to_address?

  belongs_to :newspaper
  has_many :libraries
  has_many :users, through: :libraries
  mount_uploader :photo, PhotoUploader
  mount_uploader :media, PhotoUploader

  scope :published, -> { where.not(publication: nil).where("publication > ?", Time.zone.now)}

  def properties
    {title: title, summary: summary, url: "/articles/#{id}", img: self.try(:photo).try(:url)}
  end

end

Модель библиотеки:

class Library < ApplicationRecord
  belongs_to :article, optional: true
  belongs_to :user, optional: true
end

Проблема возникает, когда я использую обновление Контроллер статьи:

  def update
    if @article.users.include?(@user)
       @article.users.delete(@user)
    else
       @article.users.push(@user)
    end
    @article.save!
    redirect_to article_path(@article)
  end

Я получил следующее сообщение об ошибке:

PG::UniqueViolation at /articles/1

ERROR:  duplicate key value violates unique constraint "index_libraries_on_user_id"
DETAIL:  Key (user_id)=(3) already exists.

Ваша помощь была бы драгоценной!

...