用户与其他用户的关系

时间:2014-09-24 19:48:02

标签: ruby-on-rails ruby activerecord migration

我正在尝试创建一个其他用户的父模型。 这就是我现在所拥有的:

型号:

class User < ActiveRecord::Base
 .
 .
 .
  has_one :guardian_of_child
end


class GuardianOfChild < ActiveRecord::Base

  belongs_to :user, foreign_key: "guardian_id"
  has_many :users, foreign_key: "child_id"

end

迁移:

class CreateGuardianOfChildren < ActiveRecord::Migration
  def change
    create_table :guardian_of_children do |t|
      t.references :user, index: true

      t.timestamps
    end
  end
end

当我尝试访问&#39; guardian_id&#39;或者&#39; child_id&#39;

<% @guardian_of_children.each do |guardian_of_child| %>
  <tr>
    <td><%= guardian_of_child.user.guardian_id %></td>

它给了我这个错误:

undefined method `guardian_id' for nil:NilClass

我做错了什么?有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我得到了它的工作。基本上是父母与子女关系模型。

  class User < ActiveRecord::Base

    has_many :guardian_of_children, foreign_key: "guardian_id"
    has_many :child_of_guardians, class_name: "GuardianOfChild", foreign_key: "child_id"

  end

  class GuardianOfChild < ActiveRecord::Base

    belongs_to :guardian, class_name: 'User', foreign_key: 'guardian_id'
    belongs_to :child, class_name: 'User', foreign_key: 'child_id'

  end