[英]Rails, validate has_many through association with attribute value of children
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. 这意味着User
可以拥有自己的GameAccounts
,其他Users
可以将其添加到收藏夹。
I have added scope
in order to prevent one user to have multiple favorites of the same GameAccount
. 我添加了scope
,以防止一个用户拥有同一GameAccount
多个收藏夹。 However, there is one problem. 但是,有一个问题。 User can add to favorite his own GameAccount . 用户可以将自己的GameAccount添加到收藏夹。 How to prevent user adding his own GameAccount
to favorites? 如何防止用户将自己的GameAccount
添加到收藏夹?
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验证案例,因此建议您编写自己的自定义代码。
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中有很多执行自定义验证的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.