我对 Rails 和一般数据库工作非常陌生。我试图简单地显示所有作为“经理”的residence_staff成员的列表以及他们工作的hallOfResidence的hallName。residence_staff是1个表,其中包含字段“fName”和大厅名称作为外键HallOfResidence 表。如何连接两个表并将其显示到屏幕上?
目前我仅显示所有 Residence_staff 成员的列表。
员工模型:
class ResidenceStaff < ApplicationRecord
validates :fName, presence: true
end
大厅模型:
class HallOfResidence < ApplicationRecord
end
Controller :
class HomeController < ApplicationController
def index
@residence_staff = ResidenceStaff.all
end
end
查看
<h1>Title</h1>
<div>
<% @residence_staff.each do |residence_staff| %>
<%= residence_staff.fName%>
<% end %>
</div>
最佳答案
买者自负:代码未经测试。
鉴于类似的内容(您确实应该使用 hall_of_residence_id
作为外键):
# == Schema Information
#
# Table name: residence_staffs
#
# id :integer not null, primary key
# first_name :string
# hall_of_residence_id :integer
# position :string
# created_at :datetime not null
# updated_at :datetime not null
#
class ResidenceStaff < ApplicationRecord
validates :first_name, presence: true
belongs_to :hall_of_residence
class << self
def managers
where(position: 'manager')
end
end
end
还有:
# == Schema Information
#
# Table name: hall_of_residences
#
# id :integer not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
class HallOfResidence < ApplicationRecord
has_many :residence_staffs
end
看起来您应该能够执行类似的操作(有关 includes
的信息,请参阅 Guide):
class HomeController < ApplicationController
def index
@residence_staffs = ResidenceStaff.all
@residence_staff_managers = ResidenceStaff.managers.includes(:hall_of_residence)
end
end
还有:
<h1>Title</h1>
<div>
<% @residence_staff_managers.each do |residence_staff| %>
<%= residence_staff.first_name>
<%= residence_staff.hall_of_residence.name >
<% end %>
</div>
关于mysql - 如何在 Ruby on Rails 中连接 MySQL 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50034942/