Arel
Arel

Reputation: 3938

Sorting based on column in join model in Rails

I followed this RailsCast to make a sortable list of items, which works great for one model, but I need to sort items that are organized by a join model, and can't figure out how to do it. Here is an example:

I want to organize all the cycles that are in a program by the cycle_order column.

The cycle_order column is in the cycles_programs table

For good measure, see picture of the join table at the bottom.

class Cycle 

  has_many :cycles_programs
  has_many :programs, :through => :cycles_programs

  accepts_nested_attributes_for :programs
  accepts_nested_attributes_for :cycles_programs, allow_destroy: :true

class CyclesProgram

  belongs_to :program
  belongs_to :cycle

class Program 

  has_many :cycles_programs
  has_many :cycles, :through => :cycles_programs

  accepts_nested_attributes_for :cycles
  accepts_nested_attributes_for :cycles_programs, allow_destroy: :true

Here is the Schema:

create_table "programs", :force => true do |t|
    t.string   "name"
    t.datetime "created_at",    :null => false
    t.datetime "updated_at",    :null => false
  end

create_table "cycles_programs", :force => true do |t|
    t.integer  "program_id"
    t.integer  "cycle_id"
    t.integer  "cycle_order"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

create_table "cycles", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

enter image description here

Upvotes: 0

Views: 395

Answers (2)

Pedro Nascimento
Pedro Nascimento

Reputation: 13926

Add a default scope to CyclesGroup

default_scope -> { order(:group_order) }

Upvotes: 1

Arel
Arel

Reputation: 3938

And the answer is so simple. Just add default_scope -> { order(:cycle)order) } to the CyclesProgram model

Upvotes: 0

Related Questions