mysql - Rails 认为我的连接表有不同的列名

标签 mysql ruby-on-rails sql-server model-view-controller

我正在尝试在 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_idphoto_id ,而实际上是 albumIDphotoID。我应该首先从哪里查找问题的原因?这是我的三个模型。

专辑:

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/

相关文章:

mysql - 在 Django ORM 中选择中间行

mysql - 根据搜索从另一个表获取数据?

ruby-on-rails - Ruby on Rails - f.label 上的 Completed 500 内部错误

sql-server - Microsoft Visual Studio 2017 Shell 的缺失组件(已隔离)

php - 如何从查询中循环遍历数组以返回总数?

ruby-on-rails - 正则表达式攻击向量?

ruby-on-rails - 如何将 Postgres 数据库从一个 Elastic Beanstalk 环境复制到另一个 Elastic Beanstalk 环境?我正在使用 Rails 5

sql-server - 以另一个用户身份执行存储过程

SQL Server 对象名称

mysql - 从边界坐标列创建mysql多边形列