在 Rails 3 中传递虚拟属性值以形成元素 [英] Passing virtual attribute values through to form elements in Rails 3

查看:33
本文介绍了在 Rails 3 中传递虚拟属性值以形成元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有以下内容:

I have the following in my model:

before_validation :update_temp

attr_accessor :temp_int, :temp_dec

def update_temp

    self.temp = temp_int.to_f + (temp_dec.to_f / 10)

end

我认为有以下几点:

<%= f.select(:temp_int, ["97", "98"], { :include_blank => true })%> . 

<%= f.select(:temp_dec, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], { :include_blank => true })%>

这对于保存温度值非常有用.然而,有一个问题.通常在编辑屏幕上,选择助手会预先选择现有的值.但是使用虚拟属性不会发生这种情况.

This works great for saving the temperature values. However, there's one issue. Normally on the edit screen, the select helper would have the existing values pre-selected. But using the virtual attributes this isn't happening.

如何确保 temp_int 和 temp_dec 值被传递到视图?

How do I make sure that the temp_int and temp_dec values get passed to the view?

推荐答案

视图访问属性应该没有问题,但是属性是否在视图的操作中被初始化?看起来,如果您刚刚加载了模型的一个实例,那么无论 #temp 的值如何,这些属性仍然为零.

The view should have no problem accessing the attributes, but have the attributes been initialized within the view's action? It looks like, if you've just loaded an instance of the model, those attributes are still nil, regardless of the value of #temp.

请注意,如果您的操作重定向,浏览器将建立新连接以访问后续操作,并且无法访问原始操作中使用的模型实例.

Note that if your action redirects, the browser will make a new connection to access the subsequent action, and will not have access to the model instance that was use in the original action.

也许,您需要添加如下内容:

Perhaps, you need to add something like the following:

after_initialize :init_temp_parts

def init_temp_parts
  return if temp.blank?
  @temp_int = temp.to_i
  @temp_dec = temp - @temp_int
end

这篇关于在 Rails 3 中传递虚拟属性值以形成元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆