【问题标题】:Accessing existing database's tables with JOIN使用 JOIN 访问现有数据库的表
【发布时间】:2015-11-17 22:28:09
【问题描述】:

我在MySQL 中有一个现有的数据库,其中包含与many-to-many 关系的表:

  1. location
  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 以某种方式消除错误并打印正确的值。

【问题讨论】:

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


    【解决方案1】:

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

    has_and_belongs_to_many :locations, join_table: 'location_channel'
    

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

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 2016-05-18
      • 2013-06-09
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多