Finding matches from an array rails -
patient
have array of clinician
id's shared stored in shared_with
. list of patients
current user, clinician, has id stored in patient's
shared_with
what have tried doesn't work:
@shared = patient.find_by(shared_with: current_user.clinician.id).order("first_name asc")
for example, our current_user
associated clinician.id
1 , there patients
shared_with
values of 1, 4
patient
10 , 1, 7
patient 15. want @shared
list patient
10 , 15.
patient
model:
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
as far can tell, patient model doesn't need belongs_to
clinicians, , doesn't need clinician_id -- unless these related in fashion...in case, carry on.
assuming database supports array field (such postgres) you're close. need wrap in braces , since it's in quotes, you'll need #{} set interpolation. so:
patient.where(shared_with: "{#{current_user.clinician.id}}").order("first_name asc")
doing test mock modeling provided see in console:
2.1.1 :005 > current_user = user.first user load (0.8ms) select "users".* "users" order "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".* "clinicians" "clinicians"."user_id" = $1 order "clinicians"."id" asc limit 1 [["user_id", 1]] patient load (0.7ms) select "patients".* "patients" "patients"."shared_with" = '{1}' order 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"]>]>
Comments
Post a Comment