更新 .order 字段后索引顺序不会更改



一点背景:这是一款专为管理狗窝而设计的应用程序,因此您可以check-in患者并check-outcheck-in时,has_current_stay字段更新为truecheck-out时则相反。

因此,对于我的应用程序,我有一个 patient 类型的模型,在控制器中具有index方法,如下所示:

def index
    @patients = Patient.search(params[:search]).order(:has_current_stay)
    if @patients.count == 1
      redirect_to @patients.first
    end
end

索引正常工作,直到我check-out患者,此时它们再次浮动到列表顶部 - 即使它们的has_current_stay字段应该阻止它们位于顶部。我需要在结账时以某种方式"刷新"索引吗?

FWIW:check-out是通过在患者相关的stay上呼叫destroy来完成的。以下是stays controller中的destroy方法。

  def destroy
    @stay = Stay.find(params[:id]).destroy
    @runn = Runn.find_by_id(@stay.runn_id)
    @runn.occupied = false
    @runn.save
    @patient = Patient.find(@stay.patient_id)
    @patient.has_current_stay = false
    @patient.save

    flash[:success] = "Checked out #{@patient.name}"
    redirect_to patients_url
  end

任何指导都值得赞赏。

编辑:请求patients#index时的SQL查询:

Started GET "/all_patients" for ::1 at 2016-04-25 15:26:04 -0500
  ActiveRecord::SchemaMigration Load (0.5ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by PatientsController#index as HTML
  User Load (1.9ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 3]]
   (0.8ms)  SELECT COUNT(*) FROM "patients"
  Rendered shared/_search_an_index.html.erb (0.7ms)
  Patient Load (1.3ms)  SELECT "patients".* FROM "patients"  ORDER BY "patients"."has_current_stay" DESC
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 3]]
  Stay Load (0.6ms)  SELECT  "stays".* FROM "stays" WHERE "stays"."patient_id" = $1  ORDER BY "stays"."id" DESC LIMIT 1  [["patient_id", 2]]
  Runn Load (0.6ms)  SELECT  "runns".* FROM "runns" WHERE "runns"."id" = $1  ORDER BY ident ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "stays".* FROM "stays" WHERE "stays"."patient_id" = $1  ORDER BY "stays"."id" DESC LIMIT 1  [["patient_id", 2]]
  CACHE (0.0ms)  SELECT  "runns".* FROM "runns" WHERE "runns"."id" = $1  ORDER BY ident ASC LIMIT 1  [["id", 1]]
  Stay Load (0.4ms)  SELECT  "stays".* FROM "stays" WHERE "stays"."patient_id" = $1  ORDER BY "stays"."id" DESC LIMIT 1  [["patient_id", 35]]
  Runn Load (0.3ms)  SELECT  "runns".* FROM "runns" WHERE "runns"."id" = $1  ORDER BY ident ASC LIMIT 1  [["id", 2]]
  CACHE (0.0ms)  SELECT  "stays".* FROM "stays" WHERE "stays"."patient_id" = $1  ORDER BY "stays"."id" DESC LIMIT 1  [["patient_id", 35]]
  CACHE (0.0ms)  SELECT  "runns".* FROM "runns" WHERE "runns"."id" = $1  ORDER BY ident ASC LIMIT 1  [["id", 2]]
  Rendered patients/index.html.erb within layouts/application (158.0ms)
  Rendered layouts/_shim.html.erb (0.3ms)
  Rendered layouts/_header.html.erb (2.4ms)
Completed 200 OK in 643ms (Views: 560.0ms | ActiveRecord: 18.5ms)

.order(:has_current_stay)正在布尔字段上进行升序排序。由于您正在设置@patient.has_current_stay = false,这将有效地将其置于列表顶部,因为false的行为类似于零值。

尝试执行降序排序:order(has_current_stay: :desc)将用户has_current_stay值保留在底部。

最新更新