我正在尝试在 Rails 应用程序中创建照片和相册之间的多对多关系。我的连接表在 MySQL 数据库中如下所示:
+---------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+-------+
| photoID | int(10) unsigned | NO | MUL | NULL | |
| albumID | int(10) unsigned | NO | MUL | NULL | |
+---------+------------------+------+-----+---------+-------+
但是,当我进入 Rails 控制台并查询时:
photo = Photo.find(1)
photo.albums
由于生成的 MySQL 查询,我收到 Unknown columns 'albums_photos.photo_id' in 'where Clause'
错误:
SELECT `albums`.*
FROM `albums`
INNER JOIN `albums_photos`
ON `albums`.`albumID` = `albums_photos`.`album_id`
WHERE `albums_photos`.`photo_id` = 1
从数据库中可以看到,键不是 album_id
和 photo_id
,而实际上是 albumID
和 photoID
。我应该首先从哪里查找问题的原因?这是我的三个模型。
专辑:
class Album < ApplicationRecord
has_and_belongs_to_many :photos
end
照片:
class Photo < ApplicationRecord
has_and_belongs_to_many :albums
end
相册照片:
class AlbumPhoto < ApplicationRecord
belongs_to :photo
belongs_to :album
end
(注意:如果该信息有帮助的话,我将此数据库直接从 .sql 文件导入到 MySQL,而不是通过迁移。)
最佳答案
试试这个:
class Album < ApplicationRecord
has_and_belongs_to_many :photos, :association_foreign_key => 'photoID'
end
class Photo < ApplicationRecord
has_and_belongs_to_many :albums, :association_foreign_key => 'albumID'
end
编辑
您的迁移是否如下所示:
create_table :albums_photos do |t|
t.integer :album_id
t.integer :photo_id
t.timestamps
end
关于mysql - Rails 认为我的连接表有不同的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38795089/