Rails association - 现有列表中项目的自定义列表

Rails association - Customised list of items from existing list

我正在开发一个 rails 应用程序,用户可以在其中将他们希望执行的任务添加到他们自己的自定义列表中。每个任务也可以属于 0 个或多个类别。到目前为止我试过这个:

user.rb

has_one :user_list
has_many :tasks, through: :user_list

user_list.rb

belongs_to :user
has_many   :tasks

tasks.rb

has_and_belongs_to_many :categories

[时间戳}_migration.rb

create_table :user_lists do |t|
  t.integer :user_id
  t.integer :task_id

  t.timestamps null: false
end

我遇到的问题是在控制台中我尝试 运行 User.find(1).tasks 使用以下查询时找不到列 tasks.user_list_id:

SELECT "tasks".* FROM "tasks" INNER JOIN "user_lists" ON "tasks"."user_list_id" = "user_lists"."id" WHERE "user_lists"."user_id" = ?  [["user_id", 1]]

此查询应该将任务 table 中的任务 ID 与 user_lists table 上的任务 ID 结合起来。关联是否正确?如果正确,我该如何更改查询?

要允许将任务放在多个列表中,您需要一个 M2M 连接 table,它连接 user_liststasks table.

class User < ActiveRecord::Base
  has_many :user_lists
  has_many :tasks, through: :user_lists
end

class Task < ActiveRecord::Base
  has_many :user_list_items
  has_many :user_lists, through: :user_list_items
end

class UserListItem < ActiveRecord::Base
  belongs_to :task
  belongs_to :user_list
  has_one :user, through: :user_list
  # optional
  validates_uniqueness_of :task_id, scope: :user_list_id
end

class UserList < ActiveRecord::Base
  belongs_to :user
  has_many :user_list_items
  has_many :tasks, through: :user_list_items
end

您可以使用以下方法创建连接模型和迁移:

rails g model UserListItem user_list:belongs_to task:belongs_to

您可能还想打开迁移并添加复合索引:

add_index :user_list_items, [:user_list_id, :task_id], unique: true

将其设置为唯一是可选的 - 但在大多数情况下,您希望连接 table 条目对于 table A 和 B 是唯一的。

参见:

您的用例要求将一项任务分配给多个用户,而一个用户只有一个任务列表。这听起来像是 userstasks 之间的 HABM 关联。

最简单的表达方式是:

class User
  has_and_belongs_to_many: :tasks
  ...
end

class Task
  has_and_belongs_to_many: :users
  ...
end

和创建连接的迁移 table:

create_join_table :users, :tasks, do |t|
  t.index :user_id
  t.index.task_id
end

您不需要创建 TaskUser 模型来匹配联接 table 直到您需要跟踪其他属性。 Rails 会自动处理。

如果用户需要多个任务列表,您将需要该 TaskList 模型。让我知道,我会更新我的答案。

这是关于 HABM and join migration

的文档