0

Trying to store objects in an array to iterate through in the view.

In my controller:

def expire
  @search = Search.new(search_params)
  if @search.valid?
    @clients = []
    @allClients = #value from REST API
    @allClients.each do |client|
      @clientele = Clientele.new
      @clientele["exp"] = client.experience  ##Also tried @clientele.exp = client.experience
      @clientele["email"] = client.email  ##Also tried @clientele.email = client.email
      @clients.push(@clientele)
    end
  end
end
class Clientele
  def exp
  end
  def email
  end
end  

In my view nothing shows up and showing the @clients array gives an empty array:

<% @clients.each do |client| %>
  <%= client.exp %>
  <%= client.email %>
<% end %>
<%= clients %> #=> []

I'm not sure what I'm doing wrong, I can't seem to just create a temporary object to store values in and store it into an array. Any help or suggestions would be helpful.

Corey
  • 835
  • 1
  • 9
  • 32

1 Answers1

0

You never initialize @allClients (at least in the code you provided). So, @allClients is nil and @allClients.each produces nothing.

Try something more like:

def expire
  @search = Search.new(search_params)
  if @search.valid?
    @clients = Client.all.map do |client|
      Clientele.new(
        exp: client.experience,
        email: client.email
      )
    end
  end
end    

Using map returns an Array populated by the result of the block (which is an initialized Clientele object).

Are you going to add some more code in? I assume you are. Because, as currently written, the whole Clientele instantiation thing seems kind of pointless.

You can make your Clientele class like this:

class Clientele

  def initialize(params={})
    params.each do |k,v|
      class_eval{attr_accessor k}
      send("#{k}=",v)
    end
  end

end 

And then you'll be able to instantiate it the way I show. The class_eval bit creates the getters and setters. The send bit assigns the passed-in parameters to their respective variables.

If you want to skip the Clientele class altogether, you could do:

def expire
  @search = Search.new(search_params)
  if @search.valid?
    @clients = Client.all.map do |client|
      {exp: client.experience, email: client.email}
    end
  end
end  

In which case you'll need to change your erb to:

<% @clients.each do |client| %>
  <%= client[:exp] %>
  <%= client[:email] %>
<% end %>
<%= clients %> #=> []

Or, if you like your erb the way it is, you could do:

def expire
  @search = Search.new(search_params)
  if @search.valid?
    @clients = Client.all.map do |client|
      OpenStruct.new(exp: client.experience, email: client.email)
    end
  end
end  

In which case, you can still do:

<% @clients.each do |client| %>
  <%= client.exp %>
  <%= client.email %>
<% end %>
<%= clients %> #=> []  
jvillian
  • 19,953
  • 5
  • 31
  • 44