【问题标题】:Has many through stop printing the entire object after loop循环后有许多通过停止打印整个对象
【发布时间】:2015-05-15 01:07:32
【问题描述】:

我正在练习 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 方法时一样。

【问题讨论】:

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


    【解决方案1】:

    将第一行的开头从&lt;%= 更改为&lt;%

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

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多