验证关联表属性的唯一性



我正在努力实现以下目标:

  • 创建一个验证器,以确保每个用户都有一个唯一的相册"名称">

请参阅下面的代码:

合作.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

用户.rb

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

白蛋白_控制器.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

我在相册模型中尝试了以下内容:

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

还有一些像这样的自定义验证器:https://github.com/rails/rails/issues/20676为嵌套形式工作,但所有这些都没有成功。

我没主意了。。非常感谢您的帮助

好的,得到了:

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

最新更新