0

sorry for the lame question, but I'm new to ruby on rails and I'm trying to list all objects of a model when I'm rendering the 'new' view of another model and I'm getting an error

I have my cliente_controller.rb that has:

class ClientesController < ApplicationController
  before_action :set_cliente, only: [:show, :edit, :update, :destroy]

  # GET /clientes/new
  def new
    @cliente = Cliente.new
    @advogados = Advogado.find(:all)
  end

and at my cliente/new.html.erb I have:

  <% @advogados.each do |advogado| %>
    <%= @advogado.nome %>
  <% end %>

and the error thrown is:

    undefined method `nome' for nil:NilClass

but when I do:

  <%= @advogados %>

It prints:

[#<Advogado id: 5, nome: "Adv1", created_at: "2014-05-02 13:58:33", updated_at: "2014-05-02 13:58:33">, #<Advogado id: 6, nome: "Adv2", created_at: "2014-05-02 13:58:48", updated_at: "2014-05-02 13:58:48">] 

So @advogados is not null, but somehow I can't access the variables when looping through it. Any ideias?

Thanks

4 Answers 4

4
<%= advogado.nome %>

Not

<%= @advogado.nome %>
Sign up to request clarification or add additional context in comments.

Comments

2

Your code is iterating over your list of @advogados and storing each one in the variable advogado for the duration of the block.

Inside the block you should be using advogado, not @advogado. So call advogado.nome.

Comments

1

@advogado.nome should be advogado.nome , check this instance variables in ruby on rails

<% @advogados.each do |advogado| %>
   <%=advogado.nome%>
<% end %>

Comments

1

Is <%= advogado.nome %> because you are redefined into the each.

Comments

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.