【问题标题】:How to join MySQL tables in Ruby on Rails?如何在 Ruby on Rails 中加入 MySQL 表?
【发布时间】:2018-04-26 04:40:51
【问题描述】:

我对 Rails 非常陌生,并且通常使用数据库。我正在尝试简单地显示所有“经理”的residence_staff 成员的列表以及他们工作的hallOfResidence 的hallName。residence_staff 是一张表,其中包含“fName”字段和大厅的名称作为外键hallOfResidence 表。如何连接这两个表并将其显示到屏幕上?

目前我只显示所有 Residence_staff 成员的列表。

员工模型:

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>

【问题讨论】:

  • name of the hall as a foreign key - 嗯。这听起来很糟糕。此外,fName 不是常规命名。如何确定ResidenceStaff 是否为经理?
  • 他们有一个名为 position 的字段,其中一些是“经理”

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


【解决方案1】:

Caveat Emptor:代码未测试。

给定类似的东西(你真的应该使用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

您似乎应该能够执行以下操作(请参阅 Guide 以获取有关 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>

【讨论】:

  • 我确实将宿舍表更改为具有 int ID,现在一切正常,除了在视图中,residence_staff 无法识别 fName 字段。有什么建议吗?
  • “无法识别 fName 字段”是什么意思?你有错误吗?如果是这样,请将其添加到您的问题中。
  • 我没有得到任何错误,只是在编辑器中它不再识别 fName 是员工的一个字段。但是,当我运行时,我收到此错误:“ Hall(hallId: integer, hallName: text, street: text, city: text, postcode: integer, phoneNumber: integer, sfaffNumber: integer) 无法识别预加载“我认为有数据库迁移发生错误
猜你喜欢
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
相关资源
最近更新 更多