简体   繁体   中英

Validate length of array in rails model

I have implemented a custom tagging solution in my application. The only thing I have left is to validate the number of items in the tag_list when the user submits the form. For my Topic model, I need this to limit to one tag. I have tried all of these methods and in each version I still get the error (only 1 tag allowed), even if only one tag is present.

validates :tag_list, length: { maximum: 1 }

I have also tried:

validates :tag_list, length: {
    maximum: 1,
    message: 'Only one tag allowed for topics.'
  }

as well as:

validate :maximum_amount_of_tags

  def maximum_amount_of_tags
    number_of_tags = self.tag_list.length
    errors.add(:base, "only 1 tag allowed") if number_of_tags > 1
  end

I assume you could have something like this in your model.

class Topic

  attr_accessor :tag_list

  has_many :topic_tags
  has_many :tags, through: :topic_tags

  def tag_list=(names)
    tags = names.reject(&:empty?).uniq
    if tags.size > 1
      errors.add(:tags, "Too many tags")
      raise ActiveRecord::RecordInvalid, self
    end
    self.tags = tags.map do |name|
      Tag.where(name: name).first_or_create!
    end
  end

end

Then in your controller params could look like this:

def topic_params
  params.require(:topic).permit(:title, tag_list:[])
end

Basically this is what's going on here:

  1. You pass your tags array as tag_list , attr_accessor :tag_list allows you to access tags as I assume tag_list is not attribute of Topic model
  2. Method below a) clears empty and duplicate values, b) validates if number of tags is upon limit, c) creates tags for Topic - adds association if tag exists or creates new tags and adds association if new tag.

I hope this helps.

在maximum_amount_of_tags中,您应该尝试检查self.tag_list是否为数组类型,然后检查其长度,因为如果它为string类型,则它将检查tag_list中的字符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM