How should I fix this incorrect error message (don't quite understand the code) Question
I saw this report about a bug in an error message and figured that would be an easy fix. The incorrect error message is: "Tags can't have more than 5 tags". That should be "Posts can't have...". I figured I'd need to find and edit a string.
I grepped the code and found my way to app/models/post.rb
, which includes this:
def maximum_tags
if tags_cache.length > 5
errors.add(:tags, "can't have more than 5 tags")
elsif tags_cache.empty?
errors.add(:tags, 'must have at least one tag')
end
end
What is :tags
here? I don't see anything in this file that defines it, so it must be coming from somewhere else. (Have I mentioned I'm very much a newbie with Ruby and Rails?)
I think the logic here is that the error is being caused by tags validation, so we're adding it to a set of errors about that field. But we don't want to use the name of the field in the error message here.
I realize it's possible to hack around this problem by changing the string here to a sentence that can legitimately begin with the word "Tags", but I'd rather understand what the correct change would be.
1 answer
Rails has a whole validation logic for showing nice errors whenever things are not valid. What you are adding an error to is the tags "field" of "Post" (in app/models/post.rb
you will see a has_many :tags
). Internally, rails also uses this information when you would programmatically check "which part of this post is invalid now?". You would ideally want that to answer to remain as "tags".
Perhaps the rails guide on validations can provide more information on alternative solutions: https://guides.rubyonrails.org/active_record_validations.html .
0 comment threads