【问题标题】:Sorting based on column in join model in RailsRails中基于连接模型中的列排序
【发布时间】:2013-06-20 19:39:06
【问题描述】:

我按照this RailsCast 制作了一个可排序的项目列表,这对一个模型非常有用,但我需要对由连接模型组织的项目进行排序,并且不知道如何去做。这是一个例子:

我想按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

【问题讨论】:

    标签: ruby-on-rails sorting has-many-through jointable


    【解决方案1】:

    CyclesGroup添加默认范围

    default_scope -> { order(:group_order) }
    

    【讨论】:

      【解决方案2】:

      答案很简单。只需将default_scope -> { order(:cycle)order) } 添加到CyclesProgram 模型

      【讨论】:

        猜你喜欢
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        • 1970-01-01
        • 1970-01-01
        • 2022-10-21
        • 2012-10-23
        • 1970-01-01
        相关资源
        最近更新 更多