-1
我有一個名爲Retreat的Rails模型 Retreat與模型實例具有has_many關聯,因此Retreat具有多個實例,實例屬於Retreat。使用關聯模型上的屬性來訂購Rails模型
這裏有兩個模式:
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
我想訂購的最直接的實例的日期方面退卻模型(即是最接近今天實例的日期)。如果撤退沒有實例,則按照順序排列。
我該怎麼做?
編輯#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
可能有更好的方法來做到這一點。
實例有一個日期字段。我希望由日期字段排序而不是由created_at字段排序。因爲,撤退可能有很多事件,因此有許多日期。我想要在距離「今日」最近的日期訂購所有撤退。 – dhaliman
然後使用'date'而不是'created_at',我將更新 –
這不起作用。務虛會根本沒有得到訂單。 – dhaliman