验证关联 table 属性的唯一性

Validate uniquess of association table attribute

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

请看下面我的代码:

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

专辑

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

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

  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