简体   繁体   English

输入字段方法(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?

I have a standard Rails 2.3.5 app with a model called Post. 我有一个标准的Rails 2.3.5应用程序,模型名为Post。 Post has an attribute called url, and the following getter is defined: Post具有一个称为url的属性,并定义了以下getter:

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 (eg it returns http://foo.com if the attribute's true value is foo.com) 如果加载script/console ,则可以执行Post.first.url并获得所需的结果(例如,如果属性的真实值为foo.com,则返回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; 但是,如果我有一个form_for块,并执行类似form.text_field :url ,它将不会返回带有http://前缀的url; rather, it simply returns foo.com 相反,它只是返回foo.com

How does form_for access attributes on ActiveRecord models? ActiveRecord模型上的form_for访问属性如何? 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

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= . 如果要实现设置器以添加http://,则应将函数编写为def url=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM