与其他型号相同的型号 has_many 和 belongs_to
Same model has_many and belongs_to to other model
模型用户应该有关联:
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'
任务应该有很多执行者,只有一个负责人。如何正确建立这个公会?
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, ...]
模型用户应该有关联:
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'
任务应该有很多执行者,只有一个负责人。如何正确建立这个公会?
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, ...]