The blog of freelance Designer & Developer, David Rice.
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
- email me@davidjrice.co.uk
- phone me on +44 7590 538 303
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
- 22 Apr » HTML5 Validator.nu ruby gem
- 28 Sep » ActiveMerchant Support for Realex
- 09 Sep » Getting Real with Realex
- 04 Sep » Back in Black
- 25 Nov » Rails Session Storage Cookie Vs Active Record
- 06 Jun » Get Exceptional
- 21 Apr » git and github ftw
- 19 Apr » Co-Working Belfast, Put Your Money Where Your Mouth Is
- 28 Mar » Co-working Belfast Plan
- 26 Feb » Do Not Buy an Apple AirPort Extreme Base Station, They Crash and Burn
- 13 Feb » Ssh, Presentation in Progress