In my model, I have a simple validation like so:
class Post
validate :max_tag_limit, if: :tags
private
def max_tag_limit
errors[:tags] << "You can only have maximum of 3 tags") if tags.count > 3
end
end
The controller adds the error messages to flash like so:
if !@post.save
content = "Something went wrong - "
@post.errors.full_messages.each { |msg| content += "#{msg} : " }
flash[:error] = content
end
I display my error messages using this helper function in my ApplicationHelper module:
def flash_display
response = ""
flash.each do |name, msg|
response = response + content_tag(:div, msg, :id => "flash_#{name}")
end
flash.discard
response
end
I insert the message through js like so:
// add the flash message
$('#flash').html("<%= escape_javascript raw(flash_display) %>");
But i cannot for the life of me understand why Rails refuses to show my custom error message: "You can only have maximum of 3 tags". Instead it shows the rather cold inhuman message: "Tags is invalid :".
What am i doing wrong people? Help!
EDIT: Debugging reveals some more info, which should hopefully narrow my question.
@post.errors.full_messages
This contains only the "is invalid" message for each of my tags. I guess this means the messages i'm adding at the model, is clearly not being picked up (or is stored in the wrong location)
Seems you should use errors[:base]
instead of errors[:tags]
:
class Post
validate :max_tag_limit, if: :tags
private
def max_tag_limit
errors[:base] << "You can only have maximum of 3 tags" if tags.count > 3
end
end
And you should not be using the flash if you're not redirecting.
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.