Zoinky Zoinky - 7 months ago 9
Ruby Question

Return an array of objects to view

I am not sure what I am doing wrong with a simple example below.

I simply would like to create a list of MyImage objects, fill the name, return to the view and display all of them.

My object

class MyImage
def initialize(name)
@name = name
end
def name= name
@name = name
end
end


My Controller

class WelcomeController < ApplicationController
def index
@arr ||= Array.new
@arr.push(MyImage.new('Image1'))
@arr.push(MyImage.new('Image2'))
end
end


My View

<ul>
<% @arr.each do |t| %>
<li><%= t.name %></li>
<% end %>
</ul>


The error i get is

undefined method `name' for #<MyImage:0x86fca90 @name="Image1">


simply want to create an array of objects and display them in the view, and able to access properties of my objects inside my collection.

This is my first ruby attempt so if I am doing something totally not right please point it out as well.

Answer

A simple way, add getter for name

def name
  @name
end

You also may user attr_acessor instead writing def name= and def name

Comments