Patient
有一个clinician
个ID的数组,它们与shared_with
中存储的内容共享。我想获得patients
的列表,其中当前用户(即临床医生)将其ID存储在patient's
shared_with
我现在尝试做的事情不起作用:
@shared = Patient.find_by(shared_with: current_user.clinician.id).order("first_name asc")
例如,我们的current_user
与clinician.id
1相关联,patients
shared_with
的{{1}}值1, 4
为patient
10患者为1, 7
。我希望@shared
成为仅有patient
10和15的列表。
Patient
型号:
Patient:
clinician_id: integer
first_name: string
last_name: string
user_id: integer
shared_with: string
serialize :shared_with, Array
Patient.rb:
class Patient < ActiveRecord::Base
belongs_to :clinician
belongs_to :user
accepts_nested_attributes_for :user, :allow_destroy => true
end
答案 0 :(得分:0)
据我所知,患者模型对于临床医生来说并不需要belongs_to
,并且不需要临床医师_id - 除非这些是以另一种方式相关的......在哪种情况下,继续。
假设您的数据库支持数组字段(例如postgres),那么您非常接近。你只需要将它包装在大括号中,因为它现在在引号中,你需要一个#{}集进行插值。像这样:
Patient.where(shared_with: "{#{current_user.clinician.id}}").order("first_name asc")
使用您提供的模拟建模进行测试我在控制台中看到了这一点:
2.1.1 :005 > current_user = User.first
User Load (0.8ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, name: "benji", created_at: "2015-08-30 02:35:17", updated_at: "2015-08-30 02:35:17">
2.1.1 :006 > Patient.where(shared_with: "{#{current_user.clinician.id}}").order("first_name asc")
Clinician Load (59.0ms) SELECT "clinicians".* FROM "clinicians" WHERE "clinicians"."user_id" = $1 ORDER BY "clinicians"."id" ASC LIMIT 1 [["user_id", 1]]
Patient Load (0.7ms) SELECT "patients".* FROM "patients" WHERE "patients"."shared_with" = '{1}' ORDER BY first_name asc
=> #<ActiveRecord::Relation [#<Patient id: 2, clinician_id: nil, first_name: "tom", last_name: "jerry", user_id: nil, created_at: "2015-08-30 19:12:59", updated_at: "2015-08-30 19:26:37", shared_with: ["1"]>]>