Confirm the number of has_many elements in Ruby on Rails

Users can add tags to the snippet:

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

I want to check the number of tags: at least 1, maximum 6. How am I going to do this? Thank.

+47
validation ruby-on-rails tagging has-many
Jan 29 '11 at 12:34
source share
3 answers

You can always create a custom check .

Something like

  validate :validate_tags def validate_tags errors.add(:tags, "too much") if tags.size > 5 end 
+63
Jan 29 '11 at 12:40
source share

The best solution was provided by @SooDesuNe on this SO post

 validates :tags, length: { minimum: 1, maximum: 6 } 
+46
Jun 30 '14 at 18:37
source share

I think you can check with .reject(&:marked_for_destruction?).length .

How about this?

 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 

Or that.

 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 

Then you can specify the command.

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

Thanks for reading.

Literature:

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

+5
Feb 12 '15 at 11:56
source share



All Articles