我有两个模型,Clinician
和Patient
。 clinician
has_many: patients
和patient
belongs_to :clinician
。
除了临床医生,患者belongs_to
患者还有一个名为shared_with
的列,该列是一个包含clinician.id
数组的字符串。这是使用serialize :shared_with, Array
完成的。
我希望能够从临床医生的full_name
下拉菜单中选择仅id
数组中包含shared_with
{{}}}的临床医生。
<%= form_for [@clinician, @comment] do |form| %>
<div class="form-group">
<%= form.label :clinician_id %>
<%= form.collection_select :clinician_id, Clinician.all.order("last_name asc"), :id, :full_name, class: "form-control" %>
</div>
<div class="form-group">
<%= form.label :general_comment %>
<%= form.text_area :general_comment, class: "form-control", rows: 5, placeholder: "Leave a comment" %>
</div>
<%= form.button 'Submit Comment', class: "btn btn-u btn-success" %>
我目前在哪里Clinician.all.order("last_name asc")
我想对它进行排序,以便我只有这个较短的列表。
我认为用@clinicians
取代我现在所拥有的并将其定义为:
@patient = Patient.find_by(user_id: current_user.patient.id).shared_with
@clinicians = a list of clinicians where id: @patient.each
并使用一些能够为我做到这一点的方法。
任何建议都将不胜感激。感谢
答案 0 :(得分:1)
which is a string holding an array of
clinician.id
This terrible! Do not store the ids this way. You are trying to solve the wrong problem with your question.
Your array of shared_with ids should be a many to many relationship in the database with it's own table (Rails calls this has_and_belongs_to_many
). A patient can be shared with many clinicians and a clinician may share many patients. Read the Rails guide on many to many relationships before going further: http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference
You should end up being able to call @patient.shared_clinicians
or similar to get a list of the clinicians for the dropdown.
Your models would look something like this:
class Patient < ActiveRecord::Base
belongs_to :clinician
has_and_belongs_to_many :shared_clinicians, join_table: 'shared_patients'
end
class Clinician < ActiveRecord::Base
has_many :patients
has_and_belongs_to_many :shared_patients, join_table: 'shared_patients'
end
Then a database table shared_patients
with two columns: clinician_id
and patient_id