Ruby on rails Rails 4-验证用户是否没有';我没有超过一定数量的关系
我有以下型号Ruby on rails Rails 4-验证用户是否没有';我没有超过一定数量的关系,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,我有以下型号 class User < ActiveRecord::Base has_many :games, dependent: :destroy validates :games, length: { maximum: 3 } end class Game < ActiveRecord::Base belongs_to :user validates :user, presence: true validates_associat
class User < ActiveRecord::Base
has_many :games, dependent: :destroy
validates :games, length: { maximum: 3 }
end
class Game < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
validates_associated :user
end
class用户
我想确保没有用户拥有超过3个游戏,但验证似乎不起作用
为什么?您可以自定义验证方法。如导轨指南所示:
class用户3。
错误。将游戏添加到游戏库(“最多只能有3个游戏”)
结束
结束
结束
您可以创建自定义验证方法。如导轨指南所示:
class用户3。
错误。将游戏添加到游戏库(“最多只能有3个游戏”)
结束
结束
结束
根据,使用您拥有的代码应该可以实现
如果不起作用,您可以使用的inverse\u将相关对象存储在内存中(从而使它们可供您的验证器使用):
#app/models/user.rb
类用户
您也可以设置一个自定义方法来执行此操作:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :games, inverse_of: :user
validate :max_games
private
def max_games
errors.add(:base, "You cannot have more than 3 games on this account.") unless games.size <= 3
end
end
#app/models/user.rb
类用户
如果不起作用,您可以使用
的inverse\u将相关对象存储在内存中(从而使它们可供您的验证器使用):
#app/models/user.rb
类用户
您也可以设置一个自定义方法来执行此操作:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :games, inverse_of: :user
validate :max_games
private
def max_games
errors.add(:base, "You cannot have more than 3 games on this account.") unless games.size <= 3
end
end
#app/models/user.rb
类用户 错误。添加(:base,“此帐户上的游戏不能超过3个。”),除非使用验证设置了games.size?在行动之前怎么样?好吧,我可以这么做。但我想在当时的模型之间设置一个限制。那么,在模型中这样做是否更有意义呢?您是否将其添加为预防措施?你有什么看法?你可以隐藏创建按钮后,使用已经有3个游戏?除非你在处理API调用?是的,我可以做很多事情。但我想将其设置为验证规则此链接可以帮助您设置是否使用验证?在行动之前怎么样?好吧,我可以这么做。但我想在当时的模型之间设置一个限制。那么,在模型中这样做是否更有意义呢?您是否将其添加为预防措施?你有什么看法?你可以隐藏创建按钮后,使用已经有3个游戏?除非你在处理API调用?是的,我可以做很多事情。但我想将其设置为验证规则此链接可以帮助您
#app/models/user.rb
class User < ActiveRecord::Base
has_many :games, inverse_of: :user
validate :max_games
private
def max_games
errors.add(:base, "You cannot have more than 3 games on this account.") unless games.size <= 3
end
end