Ruby 如何通过关联从多个站点访问数据?

Ruby 如何通过关联从多个站点访问数据?,ruby,ruby-on-rails-3.2,has-many-through,Ruby,Ruby On Rails 3.2,Has Many Through,我有两个模型:患者模型和提供者模型,通过图表连接 我使用了关联“has\u many:through”[而不是“has\u and\u belien\u to\u many”],因为我需要在图表表中有另一列[称为patient\u mrn] 我想做的是展示一个给定的患者和所有相关的提供者[每个人都有自己的名字和具体的患者名称] 我通过抓取包含给定患者ID的所有图表来实现这一点。然后我可以使用 <%= chart.patient_mrn %> 提供程序模型具有: has_many :

我有两个模型:患者模型和提供者模型,通过图表连接

我使用了关联“has\u many:through”[而不是“has\u and\u belien\u to\u many”],因为我需要在图表表中有另一列[称为patient\u mrn]

我想做的是展示一个给定的患者和所有相关的提供者[每个人都有自己的名字和具体的患者名称]

我通过抓取包含给定患者ID的所有图表来实现这一点。然后我可以使用

<%= chart.patient_mrn %>
提供程序模型具有:

has_many :charts
has_many :providers, :through => :charts
has_many :charts 
has_many :patients, :through => :charts
belongs_to :patient
belongs_to :provider
图表模型有:

has_many :charts
has_many :providers, :through => :charts
has_many :charts 
has_many :patients, :through => :charts
belongs_to :patient
belongs_to :provider
然后在患者控制器中的show action中,我有:

@patient = Patient.find(params[:id])
@charts = Chart.where(:patient_id => @patient.id)
在我的患者展示视图中,我有:

<h2>Listing Providers</h2>

 <table>
  <tr>
    <th>Patient mrn</th>
    <th>Provider</th>
  </tr>

<% @charts.each do |chart| %>
  <tr>
    <td><%= chart.patient_mrn %></td>
    <td><%= chart.provider.provider_name %></td>
  </tr>
<% end %>
</table>
列出提供程序
病人mrn
供应商

这是因为您得到的是
chart.provider
nil

图表
表中,您可能有
提供程序id为空的行

提供者
表中,
图表
表中没有
提供者id
的记录(id)

试试看:

<td><%= chart.provider.try(:provider_name) %></td>


这是因为您得到的是
图表。提供者
nil
。对不起,Shweta,我是n00b,不明白。你能详细说明一下吗?