2013-06-20 52 views
0

我跟着this RailsCast創建了一個可排序的項目列表,這對一個模型非常有用,但我需要對由連接模型組織的項目進行排序,但無法弄清楚怎麼做。下面是一個示例:根據Rails中連接模型中的列進行排序

我想組織cycle_order列中的程序中的所有循環。

cycle_order列是cycles_programs

良好的措施,請參閱連接表的圖片在底部。

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 

這裏是架構:

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

回答

1

添加默認範圍CyclesGroup

default_scope -> { order(:group_order) } 
0

而答案就是這麼簡單。只需添加default_scope -> { order(:cycle)order) }CyclesProgram模型

相關問題