ruby-on-railshas-many-throughvalidates-uniqueness-of

Validate uniquess of association table attribute


I'm trying to achieve the following :

Please see my code below :

Collaboration.rb

class Collaboration < ApplicationRecord

  # Relations
  belongs_to :album
  belongs_to :user

  # Validations
  validates_uniqueness_of :user_id, scope: [:album_id]
  validates_associated :user, :album
end

User.rb

class User < ApplicationRecord

  # Relations
  has_many :collaborations
  has_many :albums, through: :collaborations

end

Album

class Album < ApplicationRecord

  # Relations
  has_many :collaborations
  has_many :users, through: :collaborations

  # Validations
  validates :name, presence: true
end

albums_controller.rb

class AlbumsController < ApplicationController

  def create
    @album = current_user.albums.new(album_params)
    @album.collaborations.new(user: current_user, creator: true)
    if @album.save
      redirect_to user_albums_path(current_user), notice: "Saved."
    else
      render :new
    end
  end

  private

    def album_params
      params.require(:album).permit(:name)
    end
end

I've tried the following in the album model :

  validates :name, uniqueness: { scope: :users }

and also some custom validators like this: https://github.com/rails/rails/issues/20676 working for nested form but all of these without any success.

I'm out of ideas.. Thanks a lot for your help


Solution

  • Ok got it :

      validates_each :name do |record, attr, value|
        if Album.joins(:collaborations).where('name = ? and collaborations.user_id = ?', record.name.downcase, record.collaborations.first.user_id).present?
       record.errors.add :name, "Album name already exists for this user"
     end