Reputation: 4999
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.
Upvotes: 0
Views: 167
Reputation: 949
A simple way, add getter for name
def name
@name
end
You also may user attr_acessor instead writing def name=
and def name
Upvotes: 0
Reputation: 4950
You have defined a setter for name
but not a getter.
You can fix this by adding this line to your class definition:
attr_reader :name
Even better, remove the explicit setter definition entirely, replacing it with a call to attr_accessor
:
class MyImage
attr_accessor :name
def initialize(name)
@name = name
end
end
You can simplify this even further using Struct
to create the class:
MyImage = Struct.new(:name)
Upvotes: 2