Reputation: 1174
I would like to display some properties of a ruby class to my view. I get a undefined method age error when I try to do so.
person.rb
attr_accessor :age
controller action
def show
@persons = Person.all
@persons.each do |p|
p.age = 25
end
end
show.html.erb view
<%= @persons.each do |p| %>
<%= p.age %>
<% end %>
Upvotes: 0
Views: 510
Reputation: 720
By the way, if Person is AR models, I advise you to use some gem like draper. It would create decorator for you model. And in decorator you can define default values, attr_accessors and it would be more elegant and practical solution. And your code would look like:
def show
@persons = Person.all.decorate
end
Upvotes: 1
Reputation: 52357
1) show
is to display a single person, not a collection (index
action is where you display the collection).
2) You should not have any troubles with displaying age
once you have defined the attr_accessor :age
in model.
So the following code is valid (even without assigning age
to any of the @persons
:
<%= @persons.each do |p| %>
<%= p.age %>
<% end %>
Having that you showed
# person.rb
attr_accessor :seats
maybe you do not have neither
# person.rb
attr_accessor :age
nor the column called age
in people
(persons
?) table.
Upvotes: 1