我收到此错误:
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。