有许多通过循环后停止打印整个对象

时间:2015-05-15 01:07:33

标签: ruby-on-rails ruby-on-rails-4 many-to-many views has-and-belongs-to-many

我正在练习has_many但是在循环浏览内容时我陷入困境。它显示整个对象而不仅仅是项目。

型号:

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Physician < ActiveRecord::Base
    has_many :appointments
    has_many :patients, through: :appointments
end

class Patient < ActiveRecord::Base
   has_many :appointments
   has_many :physicians, through: :appointments
end

控制器:

class PatientsController < ApplicationController
    def index
    @patients = Patient.all
    @appointments = Appointment.all
    @physicians = Physician.all
    end

    def show
    @patients = Physician.find(params[:id])
    @appointments = Appointment.find(params[:id])
    @physicians = Physician.find(params[:id])   
    end
end

患者/ show.html.erb:

<%= @physicians.patients.each do |physician| %> <br><br>
    <%= physician.name %>
<% end %>

输入一些随机数据进行测试后,我在http://localhost:3000/patients/1得到以下结果:

Jannie Runolfsdottir III 

Eudora Moen [#<Patient id: 4, name: "Jannie Runolfsdottir III", phone: "356-388-3102 x3079", created_at: "2015-05-14 23:09:36", updated_at: "2015-05-14 23:09:36">, #<Patient id: 5, name: "Eudora Moen", phone: "(372) 713-5045 x3012", created_at: "2015-05-14 23:09:36", updated_at: "2015-05-14 23:09:36">]

我的代码来自Views in a has_many :through relationshiphttp://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

问题是,如何停止显示整个对象?我只想显示名称。它的行为就像我使用.inspect方法一样。

1 个答案:

答案 0 :(得分:2)

将第一行的开头从<%=更改为<%

=告诉它打印返回的对象,在each的情况下是整个对象。