同一模型has_many和belongs_to到其他模型

时间:2016-12-13 21:31:13

标签: ruby-on-rails ruby-on-rails-5

模型用户应该有关联:

has_many :owner_tasks, class_name: 'Task', foreign_key: 'user_id'
has_many :doer_tasks, class_name: 'Task', foreign_key: 'doer_id'

模型任务应该有关联:

belongs_to :owner, class_name: 'User', foreign_key: 'owner_id'
has_many :doers, class_name: 'User', foreign_key: 'doer_id'

任务应该有许多实施者,只有一个所有者。如何建立这个协会?

1 个答案:

答案 0 :(得分:2)

class User
  has_many :owned_tasks, class_name: 'Task', foreign_key: :owner_id
  has_and_belongs_to_many :todo_tasks, class_name: 'Task'
end

class Task
  belongs_to :owner, class_name: 'User', foreign_key: :owner_id
  has_and_belongs_to_many :doers, class_name: 'User'
end

通过此迁移(对于Rails 5):

class RelateUsersToTasks < ActiveRecord::Migration[5.0]
  def change
    create_table :users
    create_table :tasks do |t|
      t.references :owner, index: true
    end
    create_join_table :tasks, :users do |t|
      t.index :task_id
      t.index :user_id
    end
  end
end

迁移后我相信你能够

user.owned_tasks # => [task1, task2, ...]
user.todo_tasks # => [task1, task2, ...]
task.owner # => user1
task.doers # => [user1, user2, ...]