2016-12-13 94 views
0

型號用戶應該有關聯:同一型號的has_many和belongs_to的到其他模型

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' 

任務應該有很多實幹家,只有一個所有者。建立這個協會有多合適?

回答

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, ...] 
+0

我有錯誤,當我嘗試創建任務對象'ActiveRecord的: :StatementInvalid:PG :: UndefinedTable:錯誤:關係「tasks_users」不存在' –

+0

@AlexandrDmitrenko對不起,我沒有嘗試。新版本應該可以工作。 –

相關問題