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

Accessing existing database's tables with JOIN

我在 MySQL 中有一个现有数据库,它有 table 个与 many-to-many 关系:

  1. location
  2. channel
  3. location_channel - JOIN table.

我创建了模型:

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 控制台中,我能够分别访问每个 table 的记录,例如: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

我怀疑,我需要描述 a JOIN table location_channel 以某种方式消除错误并打印正确的值.

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

has_and_belongs_to_many :locations, join_table: 'location_channel'

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