Archive for the ‘Ruby’ Category

A Note on ActiveRecord Serialization and Objects

Sunday, April 19th, 2009

Let’s say you’re serializing a ruby object for later use in a field of another model.

class Foo < ActiveRecord::Base
  serialize :bar
end

In this instance, assume an object of type “Bar” is what’s being serialized. After save, the data appears fine, but when you retrieve the data, instead of your Object you end up with yaml that looks like this:

[#<YAML::Object:0x3fcade8 @ivars={"attributes_cache"=>{}, "attributes"=>{"updated_at"=>"2008-11-04 19:33:05", "id"=>"1", "message"=>"Hello World!", "created_at"=>"2008-11-04 19:33:05"}}, @class="Bar">

This most likely means that the model of the object being serialized is not loaded yet. This can be resolved by simply doing:

class Foo < ActiveRecord::Base
  Bar

  serialize :bar
end

This will load the model before serialization occurs and you’ll be all set.

What I Learned Today About ActionView

Tuesday, January 6th, 2009

I ran across a couple of ActionView tidbits that were new to me, so I thought I’d share.

You can comment out ERb delimiters in your view by adding a pound sign before the equal sign.


<%#= str %>

When rendering a collection, you have access to a zero-based “partial_counter” variable that increments on each iteration.


<%= div_for(entry) do %>
	<%= entry_counter %>
<% end  %>

Todays lesson brought you by chapter 10 of “The Rails Way” by Obie Fernandez.