mysql - 使用 JOIN 访问现有数据库的表

标签 mysql ruby join many-to-many ruby-on-rails-4.2

我在 MySQL 中有一个现有数据库,其中包含具有多对多 关系的表:

  1. 位置
  2. channel
  3. location_channel - JOIN 表。

我已经创建了模型:

class Location < ActiveRecord::Base
    self.table_name = "location"
    has_and_belongs_to_many :channels
end

class Channel < ActiveRecord::Base
    self.table_name = "channel"
    has_and_belongs_to_many :locations
end

在 Rails 控制台中,我能够分别访问每个表的记录,例如:Location.allChannel.all

但是当我尝试通过以下方式访问给定 location 的所有 channels 时:

location = Location.first
location.channels

报错:

Mysql2::Error: Table 'mydb.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'switchboard_2_api_poc.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`

或者:

Mysql2::Error: Table 'mydb.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'switchboard_2_api_poc.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`

当我尝试时:

channel = Channel.first
channel.locations

我怀疑,我需要描述一个 JOINlocation_channel 以某种方式消除错误并打印正确的值。 p>

最佳答案

你需要告诉rails连接表的名称, 因为它猜错了。

has_and_belongs_to_many :locations, join_table: 'location_channel'

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

关于mysql - 使用 JOIN 访问现有数据库的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32183310/

相关文章:

MySQL 重写不带 IN 子句的查询

ruby - 安装了两个版本的ruby,如何解决?

php - 使用 where 条件删除一个表并连接到多个表

python - SQL:更新 A,其中 B 是 C 和 D 的每个唯一组合的最大值,其中 D 是连接表的元素

php - 如何修复 mysqli_fetch_array?我使用 php、mysqli 和 html

php - Mysqli 检索表打印标题而不是数据

PHP - 从数据库获取数据到 JSON

ruby - 使用 ruby​​ gem 时什么时候需要 'require'?

ruby-on-rails - Ruby on Rails 中的 Jasper 报告

mySQL 将多个表连接在一起