遍历 has_many 时,结果显示整个数组,而不仅仅是请求的列

When iterating through has_many, the result shows the whole array not only the requested column

我有这个代码:

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>

当我显示该迭代的数据时,它显示列,在 "case name" 中,在 [] 中,整个数组如下所示:

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">] 

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

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

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

您需要更改此行:

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

对此:

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

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