我如何建立我的任务分配关联?

How do I make my task assignment associations?

我有一个 User 模型,一个 TodoList 模型,它有很多 todoItems。我的模型是:

用户模型

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable

has_many :todo_lists
devise :database_authenticatable, :registerable,
   :recoverable, :rememberable, :trackable, :validatable
end 

TodoList 模型

class TodoList < ActiveRecord::Base
has_many :todo_items
belongs_to :user
end

ToItem 模型

class TodoItem < ActiveRecord::Base
include AASM
belongs_to :todo_list
def completed?
!completed_at.blank?
end
#belongs_to :user
#belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'    
aasm :column => 'state', :whiny_transitions => false do
    state :not_assigned, :initial => true
    state :assigned
    state :taskCompleted
end

我正在尝试修改我的模型,以便任何用户都可以请求分配一个 taskItem,并且任务所属的用户可以接受或拒绝请求。分配请求获得批准后,我希望该任务也与分配给它的用户相关联。 我该如何处理我的模型关联和关系?在此先感谢您的帮助。

您可以在 User 和 TodoItem 之间的 many-to-many 关系中使用 assignments 关联 table。您的关联 table 将有一个额外的布尔属性,指示项目所有者是否已接受请求。类似于:

class TodoItem < ActiveRecord::Base
  ...
  has_many :users, through: :assignments
  ...
end

对于User

class User < ActiveRecord::Base
  ...
  has_many :todo_items, through: :assignments
  ...
end

最后是协会 table:

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :todo_item
end

创建关联 table 的迁移如下所示:

class CreateAssignments < ActiveRecord::Migration
  def change
    create_table :assignments do |t|
      t.belongs_to :user, index: true
      t.belongs_to :todo_item, index: true
      t.boolean :request_accepted, default: false, null: false
      t.timestamps null: false
    end
  end
end