使用关联模型上的属性对Rails模型进行排序

时间:2017-06-29 07:42:07

标签: ruby-on-rails activerecord

我有一个名为Retreat的Rails模型 Retreat与模型实例具有has_many关联,因此Retreat有许多实例,实例属于撤退。

这是两者的架构:

create_table "instances", force: :cascade do |t|
 t.date "date"
 t.string "venue"
 t.string "schedule"
 t.decimal "price", precision: 8, scale: 2
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.integer "retreat_id"
 t.index ["retreat_id"], name: "index_instances_on_retreat_id"
end

create_table "retreats", force: :cascade do |t|
 t.string "title"
 t.string "tagline"
 t.string "type_of"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "description"
 t.string "schedule"
 t.boolean "available", default: false
end

我想根据最直接实例的日期(即最接近今天的实例的日期)来订购Retreat模型。如果Retreat没有实例,那么它将在订单中排在最后。

我该怎么做?

编辑#1:

这就是我最终做到的:

def Retreat.order_by_upcoming(order='asc')
  if order == 'asc'
    Retreat.find_by_sql("select retreats.* from retreats left outer join \
     (select retreats.title, min(instances.date) as upcoming, 
       count(instances.date) from retreats left outer join instances on 
       retreats.id = instances.retreat_id where 
       instances.date >= '#{Date.today}' group by retreats.title) as s on \
       retreats.title = s.title order by case when s.upcoming is null then 1 
       else 0 end, s.upcoming, retreats.title")
  elsif order == 'desc'
    Retreat.find_by_sql("select retreats.* from retreats left outer join \
      (select retreats.title, min(instances.date) as upcoming, 
       count(instances.date) from retreats left outer join instances on 
       retreats.id = instance s.retreat_id where 
       instances.date >= '#{Date.today}' group by retreats.title) as s on \
       retreats.title = s.title order by s.upcoming desc, retreats.title")
  end
end

可能有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:0)

这应该有帮助

Retreat

假设has_many Instance {{1}} s