我如何写这个 has_many_to_many 依赖项?

How do I write this has_many_to_many dependency?

我正在尝试创建 Goal 模型之间的多对多关系。一个目标可以有依赖目标,一个目标可以有依赖它的其他目标。

到目前为止我已经想出了以下方法,但它似乎没有用。

class Goal < ActiveRecord::Base
  belongs_to :goal_status
  belongs_to :goal_type

  has_many :users, through: :user_goals
  has_many :user_goals

  has_many :dependers, class_name: 'GoalDependency', foreign_key: :dependee_id
  has_many :dependees, class_name: 'GoalDependency', foreign_key: :depender_id
  has_many :dependencies, through: :dependees
  has_many :depending, through: :dependers

  validates_presence_of :goal_status_id, :goal_type_id
end


class GoalDependency < ActiveRecord::Base
  belongs_to :dependee, class_name: 'Goal', foreign_key: 'dependee_id'
  belongs_to :depender, class_name: 'Goal', foreign_key: 'depender_id'
end

架构

  create_table "goal_dependencies", force: :cascade do |t|
    t.integer  "dependee_id"
    t.integer  "depender_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "goals", force: :cascade do |t|
    t.integer  "goal_status_id"
    t.integer  "goal_type_id"
    t.string   "description"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
  end

我遇到错误

Could not find the source association(s) "dependency" or :dependencies in model GoalDependency. Try 'has_many :dependencies, :through => :dependees, :source => <name>'. Is it one of dependee or depender?

我尝试输入几个不同的值作为源,但没有任何效果。我对使用源不是很熟悉。

我猜这在 rails 中是可能的。有什么想法吗?

在听取@Pavan 的建议后,我改变了周围的语言并设法让它以这种方式工作。请参阅下面的代码。

 class Goal < ActiveRecord::Base
  belongs_to :goal_status
  belongs_to :goal_type

  has_many :users, through: :user_goals
  has_many :user_goals

  has_many :parent_goals, class_name: 'GoalDependency', foreign_key: :parent_id
  has_many :child_goals, class_name: 'GoalDependency', foreign_key: :child_id
  has_many :children, through: :child_goals
  has_many :parents, through: :parent_goals

  validates_presence_of :goal_status_id, :goal_type_id
end

class GoalDependency < ActiveRecord::Base
  belongs_to :parent, class_name: 'Goal', foreign_key: 'parent_id'
  belongs_to :child, class_name: 'Goal', foreign_key: 'child_id'
end

架构

create_table "goals", force: :cascade do |t|
    t.integer  "goal_status_id"
    t.integer  "goal_type_id"
    t.string   "description"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
end

create_table "goal_dependencies", force: :cascade do |t|
    t.integer  "parent_id"
    t.integer  "child_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
end