validationRuby on Rails中has_many项目的数量

用户可以将标签添加到代码片段中:

class Snippet < ActiveRecord::Base # Relationships has_many :taggings has_many :tags, :through => :taggings belongs_to :closing_reason end 

我想validation标签的数量:至less1,至多6.我该怎么做? 谢谢。

您始终可以创build自定义validation 。

就像是

  validate :validate_tags def validate_tags errors.add(:tags, "too much") if tags.size > 5 end 

在这个SOpost中 , @SooDesuNe提供了一个更好的解决scheme

 validates :tags, length: { minimum: 1, maximum: 6 } 

我认为你可以使用.reject(&:marked_for_destruction?).length

这个怎么样?

 class User < ActiveRecord::Base has_many :groups do def length reject(&:marked_for_destruction?).length end end accepts_nested_attributes_for :groups, allow_destroy: true validates :groups, length: { maximum: 5 } end 

或这个。

 class User < ActiveRecord::Base has_many :groups accepts_nested_attributes_for :groups, allow_destroy: true GROUPS_MAX_LENGTH = 5 validate legth_of_groups def length_of_groups groups_length = 0 if groups.present? groups_length = groups.reject(&:marked_for_destruction?).length end errors.add(:groups, 'too many') if groups_length > GROUPS_MAX_LENGTH end end 

那么,你可以指挥。

 @user.assign_attributes(params[:user]) @user.valid? 

感谢您的阅读。

参考文献:

http://homeonrails.com/2012/10/validating-nested-associations-in-rails/ http://qiita.com/asukiaaa/items/4797ce44c3ba7bd7a51f