我正在努力实现以下目标:
- 创建一个验证器以确保每个用户都有一个唯一的专辑“名称”。
请在下面查看我的代码:
协作.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适用于嵌套形式,但所有这些都没有成功。
我没有想法..非常感谢您的帮助