Lucas Santiago
Lucas Santiago

Reputation: 11

Rails ignores if and else statement

First thing, sorry for my bad english.

I have a condition that put a string in a variable in my view.

My controller

    def  index
    @hosts= Host.all

    @hosts.each do |host|
      if host.ativo?
        @status = "Sim"
      else
        @status = "Não"
      end

      if Time.zone.now > host.validade
        flash[:info] = "Você tem hosts expirados !"
        @alerta = "Expirado !"
      else
        @alerta = "Válido !"
      end
     end
    end

My view

<tbody>
    <% @hosts.each do |host| %> 

      <tr>
        <td><%= link_to host.id, host_path(host),class: 'btn btn-default btn-xs'%></td>
        <td><%= host.mac %></td>
        <td><%= host.nome %></td>
        <td><%= host.descricao %></td>
        <td><%= @status %></td>
        <td><%= host.validade.strftime("%d/%m/%Y %H:%M")%></td>
        <td><%= @alerta %></td>
        <td>
          <%= link_to t('.edit', :default => t("helpers.links.edit")),
                      edit_host_path(host), :class => 'btn btn-default btn-xs' %>
          <%= link_to t('.destroy', :default => t("helpers.links.destroy")),
                      host_path(host),
                      :method => :delete,
                      :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
                      :class => 'btn btn-xs btn-danger' %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>
</div>

But in my @alerta varibale i only get the string "Expirado" and in @status i only get "Sim" even if the @host.ativo? return false and Time.zone.now its < than host.validade

But if i put the same logic that is in controller in my view it works pretty well, i dont understand why

Upvotes: 0

Views: 73

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

Ruby most certainly doesn't ignore anything. Not on purpose. The problem is in your code. You run one loop in controller and re-assign the same two variables over and over again, for each host. So they will hold the values which were correct for the last cost.

Then you enumerate the hosts again, in the view. And just use those [wrongly] pre-calculated values.

The easiest fix here is to calculate those values directly in the view and ditch the loop in the controller.

A better thing to do would be to correctly prepare data for the view in controller. Now, several possibilities here. Either use "view models" (group a host with its view-specific data (status and alerta)) or use "presenters". Plenty of info in google by these keywords.

Upvotes: 1

Related Questions