我在 MySQL
中有一个现有数据库,其中包含具有多对多
关系的表:
位置
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
,
但是当我尝试通过以下方式访问给定 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
我怀疑,我需要描述一个 JOIN
表 location_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/