2017-07-22 60 views
0

的屬性值的關聯,我有三個型號:軌,驗證的has_many通過與孩子

class User < ApplicationRecord 
    has_many :game_accounts 
    has_many :favorite_game_accounts, through: :game_account_favorites, source: :game_account 
end 

class GameAccount < ApplicationRecord 
    belongs_to :user 
    has_many :favorite_users, through: :game_account_favorites, source: :user 
end 

class GameAccountFavorite < ApplicationRecord 
    belongs_to :user 
    belongs_to :game_account 

    validates_presence_of :user, :game_account 
    validates_uniqueness_of :user, scope: :game_account_id 
end 

這意味着User可以擁有自己的GameAccountsUsers可以將它們添加到收藏夾。

我已添加scope以防止一個用戶擁有相同的多個收藏夾GameAccount。但是,有一個問題。用戶可以添加到收藏夾他自己的GameAccount。如何防止用戶將他自己的GameAccount添加到收藏夾?

回答

1

我不確定是否有任何內置Rails驗證的情況下,所以我會建議編寫自己的自定義一個。

在您的具體情況下,您可以驗證GameAccountFavorite實例,即game_account.user_id不等於user.id

有很多方法的performing custom validation in Rails