Rails.cache error in Rails 3.1 - TypeError: can't dump hash with default proc

后端 未结 4 996
滥情空心
滥情空心 2020-11-29 04:23

I running into an issue with the Rails.cache methods on 3.1.0.rc4 (ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10]). The code works fine within the same applic

4条回答
  •  甜味超标
    2020-11-29 05:15

    Thanks to mu-is-too-short for his excellent analysis. I've managed to get my model to serialize now with this:

    def marshal_dump
      {}.merge(attributes)
    end
    
    def marshal_load stuff
      send :initialize, stuff, :without_protection => true
    end
    

    I also have some "virtual attributes" set by a direct SQL join query using AS e.g. SELECT DISTINCT posts.*, name from authors AS author_name FROM posts INNER JOIN authors ON author.post_id = posts.id WHERE posts.id = 123. For these to work I need to declare an attr_accessor for each, then dump/load them too, like so:

    VIRTUAL_ATTRIBUTES = [:author_name]
    
    attr_accessor *VIRTUAL_ATTRIBUTES
    
    def marshal_dump
      virtual_attributes = Hash[VIRTUAL_ATTRIBUTES.map {|col| [col, self.send(col)] }]
      {}.with_indifferent_access.merge(attributes).merge(virtual_attributes)
    end
    
    def marshal_load stuff
      stuff = stuff.with_indifferent_access
      send :initialize, stuff, :without_protection => true
      VIRTUAL_ATTRIBUTES.each do |attribute|
        self.send("#{attribute}=", stuff[attribute])
      end
    end
    

    Using Rails 3.2.18

提交回复
热议问题