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

时间:2016-08-05 17:45:29

标签: 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 column '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

AlbumPhoto:

class AlbumPhoto < ApplicationRecord
    belongs_to :photo
    belongs_to :album
end

(注意:我从.sql文件直接将此数据库导入MySQL,如果该信息有帮助,则不通过迁移。)

1 个答案:

答案 0 :(得分:0)

试试这个:

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