我收到了这个错误:
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。
答案 0 :(得分:2)
问题在于您的Trial
课程has_many :results
,因此当您致电r.results.variety_id
时,您尝试在一组结果上调用variety_id
方法,而不只是一。尝试使用迭代器,例如<%= r.results.map{|r| r.variety_id} %>
。
或者,您可以使用另一个块遍历结果并显示每个块的variety_id
:
<% @results.each do |r| %>
<% r.results.each do |result| %>
<%= result.variety_id %>
<% end %>
<% end %>