Validate the number of has_many items in Ruby on Rails

那年仲夏 提交于 2019-11-26 08:09:15

问题


Users can add tags to a snippet:

class Snippet < ActiveRecord::Base

  # Relationships
  has_many :taggings
  has_many :tags, :through => :taggings
  belongs_to :closing_reason

end

I want to validate the number of tags: at least 1, at most 6. How am I about to do this? Thanks.


回答1:


You can always create a custom validation.

Something like

  validate :validate_tags

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



回答2:


A better solution has been provided by @SooDesuNe on this SO post

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



回答3:


I think you can validate with using .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 this.

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.exists?
      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 command.

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

Thank you for reading.

References:

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



来源:https://stackoverflow.com/questions/4836897/validate-the-number-of-has-many-items-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!