2017-08-17 53 views
0

我在我的Rails應用程序兩款車型外鍵:report.rbuser.rb副兩款車型通過在軌

報告表

id 
assigned_user_id 
amount 
costs 
etc. 

用戶表

id 
assigned_user_id 
email 
prename 
etc. 

我知道如何將這兩個模型與belongs_to和has_man相關聯如果我使用標準的Rails邏輯(在報表上有一個user_id等)。

但由於我沒有在報表上的user_id,我想通過assigned_user_id連接兩個表,但我現在不知道如何在我的模型中指定我的關聯。

回答

1

要使別名一對多關聯使用foreign_keyclass_name選項。

class User < ApplicationRecord 
    # without foreign_key Rails would look for the inverse 
    # in reports.user_id 
    has_many :reports, foreign_key: :assigned_user_id 
end 

class Report < ApplicationRecord 
    # class_name is needed since the class name cannot be deduced by 
    # the name of the association 
    belongs_to :assigned_user, class_name: 'User' 
end 
+0

hm ok。這樣做,但如果我現在創建一個實例變量與所有報告,遍歷它(<%@ all_reports.each做|報告|%>)並做report.user.prename例如它拋出我的錯誤「未定義的方法'用戶'for#「 – Oliver