motamared
motamared

Reputation: 25

Variables in ruby on rails

I've started learning RoR and I have little issue with variables, here is my problem:

I have this partial:

<% if @user.errors.any? %>
    The form contains <%= pluralize($items, "error")%>
    <ul>
    <% messages = @user.errors.full_messages %>
    <% messages.delete "Password digest can't be blank" %>
    <% if messages.include? "Password can't be blank" %>
      <% messages.delete "Password confirmation can't be blank" %>
      <% messages.delete "Password is too short (minimum is 6 characters)"%>
    <% end %>
    <% messages.each do |msg|%>
      <li>* <%= msg %></li>
    <% end %>
    </ul>
    <% $items = messages.count %>
<% end %>

I used the global variable $items to get access to the new value of the messagesvariable. The problem is that when I refresh the page I get the old value not the new one.

What I want is being able to use the value of the variable messages in the method pluralize.

PS: I cannot change the html

Upvotes: 0

Views: 66

Answers (2)

AbM
AbM

Reputation: 7779

I am not sure why you would want to do that, but this should fix your problem:

<% if @user.errors.any? %>
    <% messages = @user.errors.full_messages %>
    <% messages.delete "Password digest can't be blank" %>
    <% if messages.include? "Password can't be blank" %>
      <% messages.delete "Password confirmation can't be blank" %>
      <% messages.delete "Password is too short (minimum is 6 characters)"%>
    <% end %>
    <% items = messages.count %>
    The form contains <%= pluralize(items, "error")%>
    <ul>
    <% messages.each do |msg|%>
      <li>* <%= msg %></li>
    <% end %>
    </ul>
<% end %>

Upvotes: 0

DiegoSalazar
DiegoSalazar

Reputation: 13521

You want to do:

<%= pluralize(@user.errors.full_messages.size, "error") %>

Global variables will stick around between requests which is why you're seeing the old value, because you set it at the bottom of your view. You don't need to use them. Using the code above you can effectively accomplish what you seemingly want.

Upvotes: 1

Related Questions