Zoinky Zoinky - 2 years ago 65
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
def name= name
@name = name

My Controller

class WelcomeController < ApplicationController
def index
@arr ||= Array.new

My View

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

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 Source

A simple way, add getter for name

def name

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download