迭代has_many时,结果显示整个数组不仅是请求的列

时间:2016-01-09 20:53:19

标签: ruby-on-rails ruby ruby-on-rails-4 has-many-through

我有这段代码:

class Property < ActiveRecord::Base
    has_many :owners, dependent: :destroy
    has_many :residents, through: :owners
end

class Resident < ActiveRecord::Base
    has_many :owners, dependent: :destroy 
    has_many :properties, through: :owners
end

class Owner < ActiveRecord::Base
    belongs_to :resident
    belongs_to :property
end

和默认生成的控制器。

我搜索了如何列出来自has_many through关系的数据,它对我有用,但不知道为什么它也会显示整个数组。

以下是视图代码:

 <tbody>

    <% @residents.each do |resident| %>
      <tr>
        <td><%= resident.name %></td>
        <td><%= resident.birthdate %></td>
        <td><%= resident.birthId %></td>
        <td><%= resident.address %></td>
        <td><%= resident.email %></td>
        <td><%= resident.tel %></td>
        <td><%= resident.properties.each do |property| %>
            <%= property.name %>
          <% end %> 
        </td>
     </tr>
    <% end %>
  </tbody>

当我显示该迭代的数据时,它会显示列,在此显示“案例名称”,并在[]中显示整个数组:

Dostojevskeho 15 
[#<Property id: 2, name: "Dostojevskeho 15", registerNumber: "9845", propertyList: 6977, propertyType: 8, created_at: "2016-01-09 20:20:04", updated_at: "2016-01-09 20:20:04">] 

enter image description here

我找不到我做错了什么。当我将它与所有教程进行比较时,我的观点对我来说很好。

这是居民控制者的一部分,有索引和显示:

class ResidentsController < ApplicationController
  before_action :set_resident, only: [:show, :edit, :update, :destroy]

  def index
    @residents = Resident.all
  end
 def show
    @residents = Resident.find(params[:id])
  end

1 个答案:

答案 0 :(得分:1)

您需要更改此行:

<%= resident.properties.each do |property| %>

到此:

<% resident.properties.each do |property| %>

删除=告诉Rails您只想迭代resident.properties。否则你会得到这种奇怪的行为,Rails试图将迭代器本身打印到页面上 - 这很少是你想要的。