I'm trying to achieve the following :
- Create a validator to be sure there is a unique album "name" per user.
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
Ok got it :