Suppose we have the need of saving an array of objects within a model. There is no obvious way to do this, since the database can only accept certain simple types, like integers, strings, booleans, etc. But the trick is way too simple. ActiveRecord allows you to call the `serialize' method on a string or text (preferably text) column, turning it into a YAML parsed array or hash. This means every time the record is saved, the array is parsed into a YAML string and stored that way, and when it is pulled from the database the array is instantly rebuilt from the string. So as far as we should be concerned, the record contains an array, and array-related methods can be called directly on the relevant attribute.
Here's a short example to clarify. Say we have a user-portal, and we want to be able to show the user the last 5 times he or she logged in. We could do this by using 5 separate date columns, but that would be cumbersome and would not serve as a good example. So our migration and user.rb files should look something like the following:
# migration file
...
create_table :users do |t|
t.text :latest_logins
...
# user.rb
attr_accessible :latest_logins ...
serialize :latest_logins
...
...
create_table :users do |t|
t.text :latest_logins
...
# user.rb
attr_accessible :latest_logins ...
serialize :latest_logins
...
Now all that's left is to take care of the logic, which should be quite simple once you're familiar with the many methods for manipulating arrays and hashes in Ruby. For instance, we could put the following code in the user model for pushing a new log-in date and popping the earliest one.
# user.rb
...
def update_logins
latest_logins.delete_at(0)
latest_logins << Time.now
self.save
end
...
...
def update_logins
latest_logins.delete_at(0)
latest_logins << Time.now
self.save
end
...
Ruby arrays and hashes are so intuitive, and have some methods that make working with them efficient and simple.
Please let me know if this post helped you, or if you have a issue or question you wish discuss.