我怎样才能确保我的has_many的大小至少为2?

时间:2011-06-21 17:24:11

标签: ruby-on-rails model

A has_many B

validates :b, ? # 

我究竟能检查到我至少有2个B?

2 个答案:

答案 0 :(得分:3)

Rails 3?尝试:

validates :b, :length => { :minimum => 2 }

答案 1 :(得分:1)

this answer你可以做到:

validate :has_at_least_two_potatoes?

def has_at_least_two_potatoes?
  errors.add_to_base "Model must have at least 2 potatoes" if self.potatoes.size < 2
end