我怎么写这个has_many_to_many依赖?

时间:2015-03-12 05:29:32

标签: ruby-on-rails ruby ruby-on-rails-4 has-many-through

我正在尝试在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?

我已尝试将几个不同的值作为源,但没有任何工作。我对使用source并不是很熟悉。

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

1 个答案:

答案 0 :(得分:1)

在接受@ 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