如何进行任务分配关联?

时间:2016-01-13 02:52:03

标签: ruby-on-rails model model-associations

我有一个用户模型,一个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,而任务所属的用户可以接受或拒绝请求。一旦分配请求被批准,我希望该任务也与分配给它的用户相关联。 我如何通过模型关联和关系来解决这个问题?在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以在User和TodoItem之间的多对多关系中使用assignments关联表。您的关联表将具有其他布尔属性,指示项目所有者是否已接受请求。类似的东西:

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

User

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

最后是关联表:

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

您创建关联表的迁移将是这样的:

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