2013-04-05 52 views
0

我有兩個型號UserDtype。 在users表中,我有兩列,名稱分別爲dtype_id和​​,其中包含D類型的ID。現在我需要通過關聯來獲取兩列值。使用@user.dtype.name會給我第一列的值(dtype_id)。在別名中的問題型號名稱導軌

現在,我還需要第二列的值,即​​。

對於這個我想這一點:

In User Model: 
belongs_to :dtype 

In Dtype Model: 
has_many :users 
has_many :dtype_seconds, :foreign_key => 'dtype_second', :class_name => "User" 

On view: 
<%= @user.dtype_seconds.name %> 

的問題是,我沒有得到任何值或錯誤。

回答

1

你添加的是有許多到dtype,但你要調用一個用戶的方法。所以你必須定義​​協會的用戶:

class User < ActiveRecord::Base 
    belongs_to :dtype 
    belongs_to :dtype_alternative, :foreign_key => 'dtype_second', :class_name => "Dtype" 

    ... 
end 

<%= @user.dtype_alternative.name %> 
+0

感謝您的回答現在有效。那是問題所在 – 2013-04-05 12:32:25

2

首先。命名。您應該將​​字段重命名爲dtype_second_id

接下來。協會。你需要適當地描述這兩個協會在這兩種模式

class User 
    belongs_to :dtype 
    belongs_to :dtype_second, :class_name => 'Dtype' 
end 

class Dtype 
    has_many :users 
    has_many :second_users, :class_name => 'User', :foreign_key => 'dtype_second_id' 
end 
+0

感謝您的答案我試過@Mischa答案和它現在的工作。 – 2013-04-05 12:33:22