有很多通过在循环后停止打印整个对象
Has many through stop printing the entire object after loop
我正在练习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
patients/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 relationship and http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
问题是,如何阻止显示整个对象?我只想显示名称。它的行为就像我使用 .inspect 方法一样。
将第一行的开头从 <%=
更改为 <%
。
=
告诉它打印返回的对象,在 each
的情况下是整个对象。
我正在练习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
patients/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 relationship and http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
问题是,如何阻止显示整个对象?我只想显示名称。它的行为就像我使用 .inspect 方法一样。
将第一行的开头从 <%=
更改为 <%
。
=
告诉它打印返回的对象,在 each
的情况下是整个对象。