2017-08-17 55 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