somple question here but pretty confusing on my side. i have a model
towns that is mapped to my towns table. can i add an extra variable to
the class and access it in my view? basicall what i am trying to do is
return a list of towns, and next to each town, display a total number of
what i have in each town.
ive tried both attr_reader and @total but no avail.
here is my view
<% for county in @counties %>
<%= county.name %>
<% for town in county.towns %>
<%= town.name %>
<%= town.total %>
<% end %>
my town model:
class Town < ActiveRecord::Base
belongs_to :county
attr_reader :total @total
Why is it that attr_accessor does not work for an AR-based class?
Thanks,
Jan
Hi Jan,
did you try to access a persistent or a non-persistent attribute?
What do you get when you @page.typus in your view, I guess nil unless
you’ve done something like @page.typus = ‘something’ before…
Regards
Florian
Hi Florian,
it’s a non-persistent attribute, calculated on the fly based on another
attribute (it’s actually a string to be used as a CSS classname).
@page.typus won’t work, because I use the instance variable @children to
store a list of Page objects (which in turn have the typus attribute):
This is what happens in the controller:
@children = Page.find(:all, :conditions => “mother_id = #{page.id}”,
:order => “position asc, title asc”) @children.each do |child|
child.author = nil if child.author == page.author
child.typus = (child.visible_children != nil) ? ‘Node’ : ‘Page’
end
This does set @typus for each child page correctly (I inspected the
children), but I cannot access the instance variable (like child.typus)
when doing only “attr_accessor :typus” in the model.
I’m very curious about this one. For me, declaring accessors, has always
worked in my whole rails code…
The objects in children in your view are really instances of Page? Did
you make a child.inspect in vour view or child.methods.sort or maybe
even child.instance_variable_get(:@typus)?
I use inspect and methods(+grep) very often at frontend debugging…
I’m very curious about this one. For me, declaring accessors, has always
worked in my whole rails code…
The objects in children in your view are really instances of Page? Did
you make a child.inspect in vour view or child.methods.sort or maybe
even child.instance_variable_get(:@typus)?
I use inspect and methods(+grep) very often at frontend debugging…
Regards
Florian
Ok, here’s a simplified version of my setup (the model lists the three
variants of implementing an attribute, of which variant 1) does not
work):
Model:
class Page < ActiveRecord::Base
belongs_to :author
1)
attr_accessor :typus
2)
def typus=(typus_value)
write_attribute(:typus, typus_value)
end
def typus
read_attribute(:typus)
end
3)
def typus
visible_children ? ‘Knoten’ : ‘Seite’
end
end
The controller needs to iterate over each child for variants 2) and 3)