2012-02-20 53 views
1

我试图使用Hash对象等为ActiveRecord的型号中表单助手:表单助手和Hash的型号为

<% hash = { :some_key => 'some_value' } %> 

<% fields_for "hash", hash do |f| %> 

    <%= f.text_field :some_key %> 

<% end %> 

据我所知,它试图拨打:some_key方法哈希对象。我试图重写哈希类的'发送'方法,但没有运气:

def send(symbol, args = []) 
    if self.has_key?(symbol) 
    self[ symbol ] 
    elsif self.has_key?(symbol.to_s) 
    self[ symbol.to_s ] 
    else 
    super 
    end 
end 

你有什么想法我怎么能用这个?

感谢您的帮助。

+0

您正在寻找与符号密钥的哈希,一个字符串。这是行不通的。但我不确定这是一个好主意,尽管我不能指出为什么...... – Chowlett 2012-02-20 16:47:36

+0

啊......你是对的。那是我的错。那是因为我确定我的钥匙是字符串。也改变了例子。谢谢 – ABrukish 2012-02-20 17:00:13

+1

您是否考虑过使用['OpenStruct'](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html)或['Struct'](http:///www.ruby-doc.org/core-1.9.3/Struct.html)而不是'Hash'? – 2012-02-20 17:41:57

回答

2

非常感谢KL-7他的OpenStruct的主张。所以,如果有人需要这个,我在这里添加完整的工作示例。

class Model < ActiveRecord::Base 

    HASH_ATTRIBUTE_DEFAULT = { 
    :value => '', 
    :selected => 0 
    } 

    serialize :hash_attribute, Hash 

    def hash_attribute 
    read_attribute(:hash_attribute) || HASH_ATTRIBUTE_DEFAULT 
    end 

    def hash_attribute=(hash) 
    write_attribute(:hash_attribute, hash) unless hash.nil? 
    end 

end 

现在是时候为OpenStruct:

<% fields_for "model[hash_attribute]", OpenStruct.new(@model.hash_attribute) do |f| %> 

    <%= f.text_field :value %> 
    <%= f.check_box :selected %> 

<% end %>