0

我有两个模型UserDtype. 在users表中,我有两个名为的列dtype_iddtype_second其中包含 Dtype 的 ID。现在我需要通过关联获取两个列的值。

使用@user.dtype.name会给我第一列(dtype_id)的值。

现在,我还需要第二列的值,即dtype_second

为此,我正在尝试:

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 %>

问题是我没有得到任何价值或错误。

4

2 回答 2

2

第一的。命名。您应该将dtype_second字段重命名为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
于 2013-04-05T12:19:43.263 回答
1

您正在添加 a has many to dtype,但您正在尝试对用户调用该方法。所以你必须定义dtype_second用户的关联:

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

  ...
end

<%= @user.dtype_alternative.name %>
于 2013-04-05T12:20:03.683 回答