I'm trying to achieve the following :
Please see my code below :
class Collaboration < ApplicationRecord
# Relations
belongs_to :album
belongs_to :user
# Validations
validates_uniqueness_of :user_id, scope: [:album_id]
validates_associated :user, :album
end
class User < ApplicationRecord
# Relations
has_many :collaborations
has_many :albums, through: :collaborations
end
class Album < ApplicationRecord
# Relations
has_many :collaborations
has_many :users, through: :collaborations
# Validations
validates :name, presence: true
end
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
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