我在MySQL
中有一个现有数据库,其中包含many-to-many
关系表:
location
channel
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.all
和Channel.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> JOIN
表location_channel
以消除错误并打印正确的值。
答案 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