我想将Active Record结果打印到我的视图中...通常我会这样做:
<% if channelList.present? %>
<% channelList.each do |channel| %>
<li>
<div class="bp-movies-list-movie">
<div class="bp-channel-list-image">
<img src="<%= channel.channelimage %>"/>
但如果我这样做,我收到了这个错误:
undefined method `channelimage' for #<Channel::ActiveRecord_Relation:0x007f2189489bd8>
我的channelList对象如下所示:
[#<ActiveRecord::Relation [#<Channel id: 1, channelname: "Smart", created_at: "2016-04-24 13:47:11", updated_at: "2016-05-05 07:40:21", channeldescription: "Coole Smarts", channelprice: 1.0, currency: "€", free: false, locked: true, channelimage: "Screenshot_2016.04.09_16h24m03s_007_.png", knowledgeprovider_id: 1>, #<Channel id: 2, channelname: "Zimmer", created_at: "2016-05-04 21:20:59", updated_at: "2016-05-04 21:20:59", channeldescription: "asdad", channelprice: 1.0, currency: "€", free: false, locked: false, channelimage: "_SEE7468.jpg", knowledgeprovider_id: 1>]>, #<ActiveRecord::Relation [#<Channel id: 5, channelname: "Emies erster Channel", created_at: "2016-05-05 08:57:56", updated_at: "2016-05-05 08:57:56", channeldescription: "asdasd", channelprice: 1.0, currency: "€", free: false, locked: false, channelimage: "2015-12-26_12.20.07.jpg", knowledgeprovider_id: 3>]>]
我的问题在哪里?
更新
获取数据:
@channelList = Array.new
@knowledgeproviderList = @user.knowledgeprovider
@knowledgeproviderList.each do |kp|
@c = Channel.where("knowledgeprovider_id = ?", kp.id)
puts @c.inspect
@channelList.push @c
end
答案 0 :(得分:3)
这个循环的Instread,并执行多个sql查询,将结果添加到数组......
@channelList = Array.new
@knowledgeproviderList = @user.knowledgeprovider
@knowledgeproviderList.each do |kp|
@c = Channel.where("knowledgeprovider_id = ?", kp.id)
puts @c.inspect
@channelList.push @c
end
映射ID并执行一个查询
@knowledgeproviderList = @user.knowledgeprovider
@channelList = Channel.where(knowledgeprovider_id: @knowledgeproviderList.map(&:id))
答案 1 :(得分:0)
出于某种原因,channelList
似乎是嵌套在数组中的ActiveRecord::Relation
。
我愿意下注<% channelList.each do |channel| %>
改为<% channelList.first.each do |channel| %>
解决此特定错误。
如果您包含控制器代码,则可能会对此问题有所了解。
答案 2 :(得分:0)
只需将您的控制器代码更改为 如果每个knowledgeprovider_id有一个频道
@channelList = Array.new
@knowledgeproviderList = @user.knowledgeprovider
@knowledgeproviderList.each do |kp|
@c = Channel.where("knowledgeprovider_id = ?", kp.id).first
puts @c.inspect
@channelList.push @c
end
如果可能有多个频道而不是更改视图代码,请执行以下操作:
<% if channelList.present? %>
<% channelList.each do |channels| %>
<% channels.each do |channel| %>
<li>
<div class="bp-movies-list-movie">
<div class="bp-channel-list-image">
<img src="<%= channel.channelimage %>"/>