我想参考buildings/index.html.erb
中的图片。我有:
class BuildingsController < ApplicationController
def index
@buildings = Building.all
@images = @buildings.images.all
end
end
class Building < ActiveRecord::Base
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :building
end
建筑物/ index.html.erb :
<% @buildings.each do |building| %>
<% if @buildings.images.any? %>
<% @buildings.images.name %>
<% end %>
<% end %>
我收到以下错误:undefined method images for <Array:0x000001109b4680>
答案 0 :(得分:2)
@buildings
是Building
个对象的数组。每个Building
对象都有images
方法。您可以迭代@buildings
数组并调用每个成员的images
方法。
<% @buildings.each do |building| %>
This is Building with ID <%= building.id %>.
<% if building.images.any? %>
...
<% end %>
<% end %>
此外,您不需要控制器中的@images
变量。
答案 1 :(得分:2)
你不是在你的建筑物上进行迭代。你需要抓住每一个,然后做你想做的事情:
<%- @buildings.each do |building| %>
<%- if building.images.any? %>
...
<%- end %>
<%- end %>
你也可以这样做:
<强> index.html.erb 强>
<%= render @buildings %>
这会占用每个Building
对象并将其传递给_building.html.erb
部分,然后您可以执行此操作
<强> _building.html.erb 强>
<%- if building.images.any? %>
...
<%- end %>