2016-08-05 47 views
0

我試圖在Rails應用程序中創建照片和相冊之間的多對多關係。我的連接表看起來像這樣的MySQL數據庫:Rails認爲我的連接表有不同的列名

+---------+------------------+------+-----+---------+-------+ 
| Field | Type    | Null | Key | Default | Extra | 
+---------+------------------+------+-----+---------+-------+ 
| photoID | int(10) unsigned | NO | MUL | NULL |  | 
| albumID | int(10) unsigned | NO | MUL | NULL |  | 
+---------+------------------+------+-----+---------+-------+ 

然而,當我進入軌道控制檯和查詢:

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 

(注:我今年進口DAT 。直接從.sql文件ABASE到MySQL,不是通過遷移,如果這些信息幫助)

回答

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 
+0

添加了此。與以前一樣的錯誤。在再次在rails控制檯中再次嘗試之前,是否需要編譯/執行更多操作? –

+0

我的不好,你可以嘗試更新的答案 – Abhi

+0

我應該將我的相冊更改爲我以前的嗎? –

相關問題