Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get validation error messages without saving

Post
  :belongs_to :user

User
  :has_many :posts

In my signup workflow they draft a Post first, then on the next page enter their User information to signup.

# intermediate step, validate that Post is valid before moving on to User creation
# posts_controller:

@post = Post.new(params[:post])
if @post.valid?
  # go on to create User
else
  render 'new'
end

BUT! @post error messages aren't created since I'm not saving the @post model I'm just checking for .valid?. How do I create the error messages without saving?

like image 617
brittohalloran Avatar asked Jun 12 '12 11:06

brittohalloran


People also ask

How do I show a validation error in a template?

To display the form errors, you use form. is_valid() to make sure that it passes validation.

Why do I keep getting a validation error?

Validation errors typically occur when a request is malformed -- usually because a field has not been given the correct value type, or the JSON is misformatted.

How can I see all validation errors in one place?

To display summarized error messagesAdd a ValidationSummary control to the page at the location where you want to display the collected error messages. Set the ErrorMessage and Display properties of the individual validation controls. (Default) Each error message appears as a bulleted item.


2 Answers

If I understand your question correctly you want to get the errors without saving the model?

That is exactly what is happening. @post.valid?

will return true or false depending on whether there are any errors. If there are errors. they will be added to @post.errorshash.

In the situation where you want to save just call @post.save It will return true if successfully saved or false if errors are present while populating @post.errors in the process

like image 65
sohaibbbhatti Avatar answered Oct 08 '22 09:10

sohaibbbhatti


According to documentation, once you've called #valid? or #invalid? on a record, #errors is populated.

like image 32
Romain Avatar answered Oct 08 '22 09:10

Romain