validate at least one in has_and_belongs_to_many

前端 未结 5 921
生来不讨喜
生来不讨喜 2020-12-18 18:33

I have a model with:

has_and_belongs_to_many :users

How do I validate that the model has at least one user in the model? I tried:

相关标签:
5条回答
  • 2020-12-18 18:43

    I would write custom validation:

    validate :has_users?
    
    def has_users?
      # rails 2:
      errors.add_to_base "Model must have some users." if self.users.blank?
    end
    

    That would do exactly that.

    Note in rails 3+ you have to use:

      # rails 3+
      errors.add :base, "Model must have some users." if self.users.blank?
    

    In rails 4+ there's a built-in shortcut, so you can simply do:

    validates :users, presence: true
    
    0 讨论(0)
  • 2020-12-18 18:55

    In Rails 3.2.x:

    validate :has_users?
    
    def has_users?
      errors.add(:base, 'Error message') if self.users.blank?
    end
    
    0 讨论(0)
  • 2020-12-18 18:55

    Try:

    validates :users, :length => { :minimum => 1 }
    
    0 讨论(0)
  • 2020-12-18 18:56

    In rails 4 you can just do

    validates :users, presence: true
    
    0 讨论(0)
  • 2020-12-18 19:06

    Josh Susser wrote a plugin that adds a validates_existence_of method that does what you want. It ensures that a foreign key references a record that exists.

    0 讨论(0)
提交回复
热议问题