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

时间:2015-08-24 13:16:09

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

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

  1. location
  2. channel
  3. location_channel - JOIN表。
  4. 我创建了模型:

    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

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

    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
    

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

1 个答案:

答案 0 :(得分:3)

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

has_and_belongs_to_many :locations, join_table: 'location_channel'

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