从另一个模型中引用一个模型

时间:2014-07-23 13:31:40

标签: ruby-on-rails

我想参考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>

2 个答案:

答案 0 :(得分:2)

@buildingsBuilding个对象的数组。每个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 %>