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:
tag_list
, attr_accessor :tag_list
allows you to access tags as I assume tag_list
is not attribute of Topic
model 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.