簡體   English   中英

驗證關聯表屬性的唯一性

[英]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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM