2

I'm writing some if/elsif statements to display error messages. When I leave the username blank and fill the other fields in correctly, it still goes to the else statement and displays "All fields must be completed." Can someone point out the error in my logic/syntax?

<% if @user.errors.any? %>
  <div id="error_explanation" class="round">

     <% if  @user[:name].nil? and @user[:email].not.nil? and @user[:password].not.nil? and @user[:password_digest].not.nil? %>      
        <h2>Please enter a valid username. </h2>


    <% else %>      <!--If any field is left blank -->
        <h2>All fields must be completed. </h2>

    <% end %>
 </div>
<% end %>

Let me know if you need anything else.

2 Answers 2

2

I think railscasts has great episode for validations http://railscasts.com/episodes/211-validations-in-rails-3

Check it out, your current approach is sure to make some troubles in the future where you need to check validations a lot.

Sign up to request clarification or add additional context in comments.

2 Comments

I created my validation tests for my user in user.rb. My code above is simply to display the error messages on the site for visitors. Is there a reason why the video approach is more effective than my current approach?
Few reasons I can think top off my head: 1) You only have to write validation once. Meanining you don't have to copy same code over and over and over. 2) Therefore makes code cleaner. 3) All Errors are nicely hashed in @object.errors. 4) Can do things like this railscasts.com/episodes/263-client-side-validations
0

Try this

<% if  @user[:name].nil? and !@user[:email].nil? and !@user[:password].nil? and !@user[:password_digest].nil? %>  

3 Comments

I tried that, but it still displays the else message. <% if @user[:name].nil? && !@user[:email].nil? && !@user[:password].nil? && !@user[:password_digest].nil? %>
Here is the debug information: name: ' ' email: [email protected] password: foobar password_confirmation: foobar
you can log the fields in the conditional statement and check if they are being set as you are thinking

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.