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?
To display the form errors, you use form. is_valid() to make sure that it passes validation.
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.
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.
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.errors
hash.
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
According to documentation, once you've called #valid?
or #invalid?
on a record, #errors
is populated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With