0

我有 3 个模型,基因型、Gmarkers 和 Gsamples,以下列方式关联:

class Genotype < ActiveRecord::Base
  attr_accessible :allele1, :allele2, :run_date
  belongs_to :gmarkers
  belongs_to :gsamples
end

class Gmarker < ActiveRecord::Base
  attr_accessible :marker
  has_many :genotypes, :dependent => :delete_all  
end

class Gsample < ActiveRecord::Base
  attr_accessible :box, :labid, :subjectid, :well
  belongs_to :gupload
  has_many :genotypes, :dependent => :delete_all
end

当我显示 Gentypes 列表(在 index.html.erb 中)时,我以以下方式显示相关数据:

<% @genotypes.each do |f| %>
  <tr>    
    <td><%= Gmarker.find(f.gmarkers_id).marker %></td>
    <td><%= Gsample.find(f.gsamples_id).labid %></td>
    <td><%= f.allele1 %></td>
    <td><%= f.allele2 %></td>
    <td><%= f.run_date %></td>
    <td><%= link_to 'Show', f %></td>
    <td><%= link_to 'Edit', edit_genotype_path(f) %></td>
    <td><%= link_to 'Destroy', f, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>

但是,页面需要一段时间才能加载,所以我想知道是否有一种更简单的方法来显示关联数据,而无需在每个循环中进行两次查找。我无法使用内置的参考 Rails 样式显示任何相关数据,例如:

f.GMarker.first.marker

但是每当我在控制台中尝试时,我都会收到一系列错误

NameError: uninitialized constant Genotype::Gmarkers

我不明白为什么控制台不知道 Gmarkers,因为他们的模型之间存在一对多的关系......

非常感谢任何帮助!

--瑞克

4

1 回答 1

0

在您的 Genotype 类中,将您的 belongs_to 声明更改为:

  belongs_to :gmarker
  belongs_to :gsample

然后在您的视图 (index.html.erb) 上,替换以下代码:

<td><%= Gmarker.find(f.gmarkers_id).marker %></td>
<td><%= Gsample.find(f.gsamples_id).labid %></td>

有了这个:

<td><%= f.gmarker.marker %></td>
<td><%= f.gsample.labid %></td>
于 2012-07-31T03:31:35.847 回答