2015-05-24 26 views
0

我有兩個模型,ClinicianPatient。 A clinicianhas_many: patientspatientbelongs_to :clinician從數組值中調用其他模型的對象rails

除了臨牀醫生患者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 

而且使用一些方法能夠幫我這個忙。

任何意見,將不勝感激。謝謝

回答

1

which is a string holding an array of clinician.id

這太可怕了!不要以這種方式存儲ID。你正試圖解決你的問題的錯誤問題。

您的shared_with ids數組應該是數據庫中的多對多關係(Rails稱其爲has_and_belongs_to_many)。患者可以與許多臨牀醫生共享,並且臨牀醫生可以共享許多患者。在繼續閱讀之前,請閱讀Rails指南中的多對多關係:http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference

您應該最終能夠撥打@patient.shared_clinicians或類似名稱來獲取臨牀醫生的下拉列表。

你的模型將是這個樣子:

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 

然後在數據庫表shared_patients有兩列:clinician_idpatient_id

+0

感謝@馬特,你是絕對正確的,使用一個表是一個更好的管理這些關係的方式。仍然學習Rails ...如果我按照你的建議創建一個'SharedPatient'表和'has_and_belongs_to_many'關係,我仍然會得到一個錯誤。我已經用一些例子爲數據庫播種了,但是當我運行'Patient.find_by(id:1259).shared_pa​​tients.first'或'Patient.find_by(id:1259).shared_clinicians.first'時,我得到了'NoMethodError:undefined方法'shared_pa​​tients'爲#或'未初始化的常量Patient :: SharedClinician'。建議嗎? – Skiapex

+0

對'SharedPatient'我添加了'belongs_to:clinicalician'和'belongs_to:patient'# – Skiapex

+0

'NoMethodError:undefined method shared_pa​​tients'for#'看起來像被調用的錯誤方法。 「Patient.find_by(id:1259).shared_clinicians」無效嗎? –

相關問題