Ruby on Rails Overwriting default accessors
In my model i say:
def dag
'test'
end
But when I loop all the records and uses
f.text_field :dag
I still do not get the value of "test"
... I get the value from the database. How can I overwrite the default getter fo开发者_如何学Pythonr forms? I works when I say
Model.dag # returns 'test'
Although your example doesn't indicate this, have you defined dag as a class method instead of an instance method? Model.dag implies that it's a class method which is not what you want.
If you could give us a little more code, it will be more useful to find the correct answer for you.
Said so, I suspect you have declared your dag
method as protected or private method.
Have a look if there is a private
(or protected
) keywork above the dag
method declaration on model's code: if so, the method is private (or protected), thus it cannot be accessed by your template...
The class:
class DenLangeKamp < ActiveRecord::Base
belongs_to :liga, :class_name => "DenLangeLiga"
DAYS = { "Man" => 1, "Tir" => 2, "Ons" => 3, "Tor" => 4, "Fre" => 5, "Lør" => 6, "Søn" => 7 }
def dag
DAYS.invert[reader_attribute(:dag)]
end
def dag=(dag)
write_attribute(:dag, DAYS[dag])
end
end
and then the form looks like this:
.........
<% liga_form.fields_for :kampe do |kamp_form| %>
<tr>
<td><%= kamp_form.text_field :dag %></td>
.........
I am saving the day as a number in the DB, so I can sort by the day. "dag" is "day" in English.
When I say like "DenLangeKamp.first.dag" I get the right return (like "Man", "Tir", etc) But in the form, I am getting the number instead! So it does not seem like it actually "overwrites" the getter method correctly.
I have the same problem. The overridden functions seem to work on the index and show but in the edit the form isn't using the overridden function. It seems to be getting a different way bypassing the overridden functions.
精彩评论