Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to sort through a polymorphic association

So - having the following setup:

class Event < ActiveRecord::Base
 has_many :invitations
end

class Invitation < ActiveRecord::Base
  belongs_to :guest, :polymorphic => true
  belongs_to :event
end

class Member > ActiveRecord::Base
  has_many :invitations, :as => :guest

  def full_name
    [first_name, last_name].join(" ")
  end
end

class Visitor > ActiveRecord::Base
  has_many :invitations, :as => :guest

  def full_name
    name
  end
end

In the end, I want to be able to fetch an Events invitations ordered by the Guests full_name. I can't figure out how - anyone who can help me solve this? Would be greatly appreciated :)

like image 332
Antony Sastre Avatar asked Dec 19 '25 13:12

Antony Sastre


1 Answers

As far as full_name is a virtual attributes I can imagine only ruby solution, not sql

event = Event.find some event
event.invitations.sort_by(&:full_name) 
like image 78
fl00r Avatar answered Dec 21 '25 06:12

fl00r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!