简体   繁体   English

验证关联表属性的唯一性

[英]Validate uniquess of association table attribute

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 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 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 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. 还有一些像这样的自定义验证器: https : //github.com/rails/rails/issues/20676适用于嵌套表单,但所有这些都没有成功。

I'm out of ideas.. Thanks a lot for your help 我没主意..非常感谢您的帮助

Ok got it : 好的,我知道了 :

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM