输入字段方法(text_area,text_field等)如何从form_for块内的记录中获取属性值? [英] How do input field methods (text_area, text_field, etc.) get attribute values from a record within a form_for block?
问题描述
我有一个标准的Rails 2.3.5应用,模型名为Post。 Post具有一个称为url的属性,并定义了以下getter:
I have a standard Rails 2.3.5 app with a model called Post. Post has an attribute called url, and the following getter is defined:
def url
p = 'http://'
u = self[:url]
u.starts_with?(p) ? u : "#{p}#{u}"
end
如果我加载了脚本/控制台
,我可以执行 Post.first.url
并获得所需的结果(例如,它返回 http://foo.com 如果属性的真实值为foo.com)
If I load up script/console
, I can do Post.first.url
and get the desired result (e.g. it returns http://foo.com if the attribute's true value is foo.com)
但是,如果我有一个 form_for
块,并执行类似 form.text_field:url
的操作,它将 not 返回带有http://前缀的网址;相反,它只是返回foo.com
However, if I have a form_for
block, and do something like form.text_field :url
, it will not return the url with http:// prefixed; rather, it simply returns foo.com
ActiveRecord模型上的form_for访问属性如何?似乎绕过了任何重载的吸气剂。
How does form_for access attributes on ActiveRecord models? It seems to bypass any overloaded getters.
推荐答案
def url_before_type_cast
p = 'http://'
u = self[:url].capitalize
u.starts_with?(p) ? u : "#{p}#{u}"
end
这篇关于输入字段方法(text_area,text_field等)如何从form_for块内的记录中获取属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!