1

I'm a n00b and still struggling with joins.

I've got two models: Patient and Provider joined through a table Chart.

I used the association "has_many :through" rather than "has_and_belongs_to_many" because i need to have another column added to the Chart table [called patient_mrn] which i cannot do with the "has_and_belongs_to_many" scenario.

What im trying to do is to show a given patient and all its associated providers [each with its specific patient_mrn]

The Patient model has:

has_many :charts
has_many :providers, :through => :charts

The Provider model has:

has_many :charts has_many :patients, :through => :charts

and the Chart model has:

belongs_to :patient
belongs_to :provider

Then in my show action in the patient controller i have:

@patient = Patient.find(params[:id])
@providers = Provider.joins(:charts)where(:charts => { :patient_id => @patient.id})

And in my patient view i have:

<h1>Listing providers</h1>

<table>
  <tr>
    <th>Provider name</th>
    <th>Patient_mrn</th>
  </tr>

<% @providers.each do |provider| %>
  <tr>
    <td><%= provider.name %></td>
    <td><%= provider.chart.patient_mrn %></td>
  </tr>
<% end %>
</table>

I realize both the controller action and the view are incorrectly written but cant figure out how to fix them.

4

1 に答える 1

1

これはうまくいくはずです:

provider_ids = @patient.charts.select(:provider_id).map(&:provider_id)
@providers = Provider.includes(:charts).find provider_ids

最初の行では、すべての患者チャートのプロバイダーを取得します。select は整数の配列ではなく、1 つのメンバー (provider_id) のみを持つ構造体の配列を返すため、マップが必要です。

2 行目では、N+1 クエリを処理する必要がないように、対応するプロバイダーを選択してグラフを含めるだけです ( http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associationsを参照) 。 .

あなたの意見に間違いはありませんが、私は間違っているかもしれません。

于 2013-04-28T10:19:48.977 に答える