0

我收到此错误:

undefined method `variety_id' for []:ActiveRecord::Relation

当我将 <%= r.results.variety_id %> 代码添加到我的试用视图时。<%= r.site.site_name %> 工作正常,但无法弄清楚为什么 <%= r.results.variety_id %> 不起作用。结果数据库有许多 trial_id (3-6),我想将它们与 Trials 数据库进行匹配,然后在我的试用视图中列出它们。

试用视图

<% @results.each do |y| %>
<h1><%= y.year %> Trials</h1>
<% end %>
<hr>
<% @results.each do |s| %>
<h3><%= s.site.site_name %></h3>
<% end %>
<hr>
<% @results.each do |r| %>
<%= r.results.variety_id %>
<% end %>

控制器

def trial
  @results = Trial.where(params[:trial_id])
end

楷模

class Trial < ActiveRecord::Base
  attr_accessible :trial_id, :site_id, :year

  scope :year, ->(year) { where(year: year) }
  scope :trial_id, ->(trial_id) { where(trial_id: trial_id) }

  belongs_to :site, :primary_key => 'site_id'
  has_many :results

end

class Result < ActiveRecord::Base
  attr_accessible :trial_id, :variety_id, :year

  belongs_to :trial

end

lass Site < ActiveRecord::Base
  attr_accessible :site_id, :site_name, :region

  has_many :trials

end

架构

 create_table "results", :force => true do |t|
    t.integer  "trial_id"
    t.integer  "variety_id"
    t.string   "year"
  end

  create_table "sites", :force => true do |t|
    t.integer  "site_id"
    t.string   "site_name"
    t.integer  "region"
  end

  create_table "trials", :force => true do |t|
    t.integer  "trial_id"
    t.integer  "site_id"
    t.string   "year"
  end

结果和试验中的 trial_id 列预先填充了相应的 id。

4

1 回答 1

2

问题是你的Trialhas_many :results,所以当你调用时r.results.variety_id,你试图variety_id在一组结果上调用方法,而不仅仅是一个。尝试使用迭代器,例如<%= r.results.map{|r| r.variety_id} %>.

或者,您可以使用另一个 each 块遍历结果并显示每个块的结果variety_id

<% @results.each do |r| %>
  <% r.results.each do |result| %>
    <%= result.variety_id %>
  <% end %>
<% end %>
于 2013-10-22T23:58:53.110 回答