I want to add multiple conditions to valid but i want to view only one summary error message.
validates :floor, presence: true, numericality: { only_integer: true }, length: { maximum: 2 }
How show only one message whenever having any error, like: "Floor is required, must be number..."
In addition, when i use:
if @posts.valid?
@posts.save
redirect_to room_path
else
render :new
end
Browser will render new with message but url is http://localhost:3000/posts , it is not http://localhost:3000/posts/new This is a problem when user refresh page => it will return index page (not new page). How can i fix it?
You can write custom validator:
validate :validate_floor
private
def validate_floor
return if floor.present? && floor.scan(/\D/).empty? && floor.length <= 2
errors.add(:floor, 'Floor is required, must be number...')
end
Other question;
When you post the form, the request goes to create
action. Because of the create
action, the path is redirected to http://localhost:3000/posts
. When there is an error in the form, the form is re-rendered with render:new
. But the url doesn't change because there is no redirect. Actually, there is no error here. This is what it should be.
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.