如何在rubyonrails中连接mysql表?

mf98qq94  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(339)

我对rails和数据库都是新手。我试着简单地显示一个列表,其中列出了所有的“经理”和他们工作的hallofresidence的名字。residence\u staff是一个表,其中字段“fname”和大厅名称作为hallofresidence表的外键。如何连接两个表并将其显示在屏幕上?
目前,我只显示一个名单,所有的工作人员。
员工模式:

class ResidenceStaff < ApplicationRecord
  validates :fName, presence: true

end

大厅型号:

class HallOfResidence < ApplicationRecord
end

控制器:

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>
qc6wkl3g

qc6wkl3g1#

注意:代码未测试。
你真的应该 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 ):

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>

相关问题