mysql - 如何在 Ruby on Rails 中连接 MySQL 表?

标签 mysql ruby-on-rails model-view-controller mariadb

我对 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/

相关文章:

MySQL 二进制日志时间戳非顺序?

MySQL 存储 1MB 的 JSON 好不好

php - MySQL/PHP 测验引擎 - 防止多次尝试

javascript - 单页应用程序(网站)的工具框架

c# - mysql存储过程,查询检查是否存在

ruby-on-rails - 如何为同一 Controller 中的所有操作呈现相同的 View ?

ruby-on-rails - rails 与设计 : How can I trigger other events when user registers?

ruby-on-rails - 当 guard-rspec 与 spork 一起使用时没有通知

javascript - CSHTML 页面上的 Javascript 元素中的 C#

javascript - 获取选定的行ID jquery数据表行选择