gpt4 book ai didi

mysql - Rails 协会 - 现有列表中的自定义项目列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:38 25 4
gpt4 key购买 nike

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

用户.rb

has_one :user_list
has_many :tasks, through: :user_list

用户列表.rb

belongs_to :user
has_many :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]]

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

最佳答案

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

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

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

参见:

关于mysql - Rails 协会 - 现有列表中的自定义项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36919887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com