Reputation: 806
I have the models Mom, Dad and Follow which is a polymorphic association. I'm trying to put the Moms and Dads that the user is following in alphabetical order for there name
attribute where their both mixed together. Here's what I want and my code so far.
Example User's Followed Mom And Dad List
Adam # Dad
Ashley # Mom
Brenda # Mom
Brian # Dad
Models
class Mom
has_many :follows, as: :followable
# columns: name
end
class Dad
has_many :follows, as: :followable
# columns: name
end
class Follow
belongs_to :user
belongs_to :followable, polymorphic: true
belongs_to :dad, -> {where( "follows.followable_type = 'Dad'")}, foreign_key: 'followable_id'
belongs_to :mom, -> {where( "follows.followable_type = 'Mom'")}, foreign_key: 'followable_id'
scope :name_order, -> { includes(:dad, :mom).order("dads.name ASC", "moms.name ASC") }
# columns: user_id, followable_id, followable_type
end
Controller
def index
@follows = current_user.follows.name_order.paginate(:page => params[:page])
end
Right now this orders them alphabetically but will put the Dads in front of the list and knock all the Moms to the bottom when I need them to mix. How would I do this?
Upvotes: 0
Views: 81
Reputation: 44715
you can try:
scope :name_order, -> {
select("#{table_name}.*, COALESCE(dads.name, mom.name) AS follow_name").
includes(:dad, :mom).references(:dad, :mom).order("follow_name")
}
Note: not tested.
However it seems that your model design is the biggest issue. Since it seems that each Mam and Dad is a user, why not use STI instead?
Upvotes: 2