如何编辑表单中的Rails序列化字段? [英] How to edit a Rails serialized field in a form?
问题描述
我的Rails项目中有一个数据模型,它有一个序列化字段:
class Widget< ActiveRecord :: Base
serialize:options
end
options字段可以有可变数据信息。例如,以下是Fixtures文件中的一条记录的选项字段:
选项:
query_id:2
axis_y:'percent'
axis_x:'text'
单位:'%'
css_class:'占用'
dom_hook:'#平均占用率'
table_scale:1
我的问题是让用户编辑的正确方法是什么这个信息在一个标准的表单视图中?
如果你只是在选项字段中使用一个简单的文本区域字段,你只会得到一个yaml转储表示,返回一个字符串。
在Rails中编辑序列化哈希字段的最佳方式是什么?
class Widget< ActiveRecord :: Base
序列化:选项
def self.serialized_attr_accessor(* args)
args.each do | method_name |
eval
def#{method_name}
(self.options || {})[:#{method_name}]
结束
def#{method_name} = (value)
self.options || = {}
self.options [:#{method_name}] = value
end
attr_accessible:#{method_name}
end
end
serialized_attr_accessor:query_id,:axis_y,:axis_x,:units
end
好处在于它将options数组的组件暴露为属性,这允许您像使用Rails窗体助手一样使用它:
#haml
- form_for @widget do | f |
= f.text_field:axis_y
= f.text_field:axis_x
= f.text_field:unit
I have a data model in my Rails project that has a serialized field:
class Widget < ActiveRecord::Base
serialize :options
end
The options field can have variable data info. For example, here is the options field for one record from the fixtures file:
options:
query_id: 2
axis_y: 'percent'
axis_x: 'text'
units: '%'
css_class: 'occupancy'
dom_hook: '#average-occupancy-by-day'
table_scale: 1
My question is what is the proper way to let a user edit this info in a standard form view?
If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.
What is the best/proper way to edit a serialized hash field like this in Rails?
If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:
class Widget < ActiveRecord::Base
serialize :options
def self.serialized_attr_accessor(*args)
args.each do |method_name|
eval "
def #{method_name}
(self.options || {})[:#{method_name}]
end
def #{method_name}=(value)
self.options ||= {}
self.options[:#{method_name}] = value
end
attr_accessible :#{method_name}
"
end
end
serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
end
The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:
#haml
- form_for @widget do |f|
= f.text_field :axis_y
= f.text_field :axis_x
= f.text_field :unit
这篇关于如何编辑表单中的Rails序列化字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!