How do input field methods (text_area, text_field, etc.) get attribute values from a record within a form_for block?

霸气de小男生 提交于 2020-01-05 03:33:06

问题


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

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)

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

How does form_for access attributes on ActiveRecord models? It seems to bypass any overloaded getters.


回答1:


def url_before_type_cast    
 p = 'http://'
 u = self[:url].capitalize
 u.starts_with?(p) ? u : "#{p}#{u}"    
end



回答2:


By returns to you mean sets?

The text field posts the data to your controller. (The create or update depending on)

In the controller:

@post = Post.new(params[:post])
or
@post.update_attributes(params[:post])

is where the field is set.

If you want to implement the setter to add the http:// you should write your function as def url=.



来源:https://stackoverflow.com/questions/2303003/how-do-input-field-methods-text-area-text-field-etc-get-attribute-values-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!