David J Rice

The blog of freelance Designer & Developer, David Rice.

08 Jun 2006

As I discovered today it’s best not to use this function with arrays created by the relationships defined in a model… why ? I’m not too sure of the specifics causing it, but here is the right and wrong way to combine two arrays of objects in ruby.

Lets use the example that we have a Person and they can send and recieve SMS (text messages) we define two finder methods for their sent and recieved messages. But if we want to display an inbox, it will have to combine them all and sort by date right?

class Person < ActiveRecord::Base
    has_many :sent_messages, :class_name => 'Sms', :foreign_key => 'sender_id', :order => 'created_at DESC'
    has_many :recieved_messages, :class_name => 'Sms', :foreign_key => 'recipient_id', :order => 'created_at DESC'

  def messages
  # The right way
     @messages = self.sent_messages | self.recieved_messages
     @messages.sort do |a, b|
        a.created_at <=> b.created_at
     end
     @messages.reverse
  end

  def messages
  # The wrong way
    @messages = self.sent_messages
    @messages.concat(self.recieved_messages)
    @messages.sort do |a, b|
       a.created_at <=> b.created_at
    end
    @messages.reverse
  end

end 
David Rice

If you need help with the Design, Build, Management, Hosting or Support of your project do get in touch, I'd love to hear from you!

Recently

Archive