Question

I'm having a little bit of a brain problem with what I think would be a simple call:

I've got:

class Channel < ActiveRecord::Base
    has_and_belongs_to_many :shows, :join_table => :channels_shows
end

class Show < ActiveRecord::Base
    has_and_belongs_to_many :channels, :join_table => :channels_shows
end

A channel has a :position and :hidden in the database (:hidden can be false, or nil if not saved as I had forgotten about defaulting to 0).
A show has :approved (same as :hidden) and of course :created_at.

I want to be able to get Channels that are (:hidden => [nil, false] ) with each channels included Shows where a show is :approved and by created_at, newest first.

I can't figure out if this is a join or an include. The closest I've gotten is this, but this doesn't sort the included shows in the right order:

Channel.order('channels.position').where(:hidden => [nil, false] ).includes(:shows).where(shows:{approved: true})

Still looking at docs and trying things in the irb; feel like it's crazy simple but I'm just not getting it.

Was it helpful?

Solution

To sort the join records, just include that sort in the order clause after your primary sort. Your channels will still have the primary sort order, but when they are equal (ie when comparing the same channel but a different show), it will fall back to sorting by the second order (effectively sorting your included table):

Channel.order('channels.position, shows.created_at').includes(:shows)...

OTHER TIPS

I think you should be able to do something like this:

class Channel < ActiveRecord::Base
  has_and_belongs_to_many :shows, :join_table => :channels_shows
  has_and_belongs_to_many :active_shows, :class_name => 'Show', :join_table => :channels_shows, :conditions => ["approved = ?", true], :order => "created_at desc"
end

To allow you to go

Channel.order('channels.position').where(:hidden => [nil, false] ).includes(:active_shows)

This is rails 3 syntax by the way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top