2017-07-22 57 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