Rails 4 - 验证用户没有超过一定数量的关系

时间:2015-12-16 04:04:00

标签: 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_associated :user

end

我想确保没有用户拥有超过3款游戏,但验证似乎不起作用。

为什么吗

2 个答案:

答案 0 :(得分:3)

您可以制作自定义验证方法。如Rails指南中所示: custom validation method

class User < ActiveRecord::Base

  has_many :games, dependent: :destroy
  validate :has_three_games_or_less

  private:

  def has_three_games_or_less
    if games.count > 3.
      errors.add_to_base("can't have more than 3 games")
    end
  end

end

答案 1 :(得分:1)

根据this documentation,使用您拥有的代码应该可以实现。

如果它不起作用,您可以使用inverse_of将关联的对象存储在内存中(从而使它们可供验证者使用):

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :games, inverse_of: :user
   validates :games, length: { maximum: 3 }
end

#app/models/game.rb
class Game < ActiveRecord::Base
   belongs_to :user, inverse_of: :games
end

您也可以设置自定义方法为您执行此操作:

#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