[英]Validate uniquess of association table attribute
我正在努力实现以下目标:
请在下面查看我的代码:
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
我在专辑模型中尝试了以下方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.