【问题标题】:How do I make my task assignment associations?如何建立我的任务分配关联?
【发布时间】:2016-01-13 02:52:03
【问题描述】:

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

用户模型

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,并且该任务所属的用户可以接受或拒绝这些请求。批准分配请求后,我希望该任务也与分配给它的用户相关联。 我该如何处理我的模型关联和关系?提前感谢您的帮助。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      相关资源
      最近更新 更多