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

时间:2016-04-25 19:05:46

标签: ruby-on-rails

一点背景:这是一款专为管理狗窝而设计的应用,因此您可check-in患者和check-out。在check-inhas_current_stay字段更新为true,而check-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是通过致电患者所关联的destroy上的stay来完成的。以下是destroy中的stays controller方法。

  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)

1 个答案:

答案 0 :(得分:0)

.order(:has_current_stay)正在对布尔字段进行升序排序。由于您设置了@patient.has_current_stay = false,因此false就像零值一样,这会有效地将其置于列表的顶部。

尝试执行降序排序:order(has_current_stay: :desc)以使用户在底部保留has_current_stay的错误值。