Rails,通过与子项的属性值关联来验证has_many

时间:2022-01-29 20:14:49

I have three models:

我有三个型号:

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

This means that User can have his own GameAccounts and other Users can add them to favorites.

这意味着用户可以拥有自己的GameAccounts,其他用户可以将其添加到收藏夹中。

I have added scope in order to prevent one user to have multiple favorites of the same GameAccount. However, there is one problem. User can add to favorite his own GameAccount. How to prevent user adding his own GameAccount to favorites?

我添加了范围以防止一个用户拥有相同GameAccount的多个收藏夹。但是,有一个问题。用户可以添加自己喜欢的GameAccount。如何防止用户将自己的GameAccount添加到收藏夹?

1 个解决方案

#1


1  

I'm not sure that there is any built-in Rails validation for you case, so I'd suggest writing your own custom one.

我不确定是否有任何内置的Rails验证,所以我建议您编写自己的自定义Rails验证。

In your particular case, you can verify on GameAccountFavorite instance, that game_account.user_id isn't equal to user.id.

在您的特定情况下,您可以在GameAccountFavorite实例上验证game_account.user_id不等于user.id.

There's plenty of ways of performing custom validation in Rails

有很多方法可以在Rails中执行自定义验证

#1


1  

I'm not sure that there is any built-in Rails validation for you case, so I'd suggest writing your own custom one.

我不确定是否有任何内置的Rails验证,所以我建议您编写自己的自定义Rails验证。

In your particular case, you can verify on GameAccountFavorite instance, that game_account.user_id isn't equal to user.id.

在您的特定情况下,您可以在GameAccountFavorite实例上验证game_account.user_id不等于user.id.

There's plenty of ways of performing custom validation in Rails

有很多方法可以在Rails中执行自定义验证