DAVID RICE

Software Developer

+44 (0) 7590 538 303

21 Ormeau Avenue
Belfast, Northern Ireland
BT2 8HD

Combining two ActiveRecord relationship created arrays

08 Jun 2006 {View Comments}

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 
«