我的模特:
class User < ApplicationRecord
has_and_belongs_to_many :comments
end
class Comment < ApplicationRecord
belongs_to :book
has_and_belongs_to_many :users
end
class CommentsUser < ApplicationRecord
belongs_to :comment
belongs_to :user
end
我可以通过连接进行常规选择:
users_ids = [197]
book_id = 659
CommentsUser.joins(:comment).where(comments: {book_id: book_id}, user_id: users_ids)
# CommentsUser Load (0.5ms) SELECT "comments_users".* FROM "comments_users" INNER JOIN "comments" ON "comments"."id" = "comments_users"."comment_id" WHERE "comments"."book_id" = $1 AND "comments_users"."user_id" = $2 [["book_id", 659], ["user_id", 197]]
但是如果我使用delete_all,它会失败(注意
"comments_users".""
:
CommentsUser.joins(:comment).where(comments: {book_id: book_id}, user_id: users_ids).delete_all
# CommentsUser Destroy (0.8ms) DELETE FROM "comments_users" WHERE ("comments_users"."") IN (SELECT "comments_users"."" FROM "comments_users" INNER JOIN "comments" ON "comments"."id" = "comments_users"."comment_id" WHERE "comments"."book_id" = $1 AND "comments_users"."user_id" = $2) [["book_id", 659], ["user_id", 197]]
# ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: zero-length delimited identifier at or near """"
# LINE 1: ...comments_users" WHERE ("comments_users"."") IN (SE...
我想使用第一个语句中使用的相同逻辑来删除记录 - 我可以找到记录,但无法删除它们 - 有什么想法吗?
在 HABTM(Has and Belongs to Many)关系中,Rails 默认情况下不会为连接表生成主键。使用联接时,Rails 会尝试引用表的主键,而缺少主键可能会在尝试删除记录时导致 SQL 语法错误。
您可以先选择记录的ID,然后进行删除操作:
CommentsUser.where(
id: CommentsUser.joins(:comment)
.where(comments: { book_id: book_id }, user_id: users_ids)
.select(:id) ).delete_all
或者,您可以使用
has_many :through
关联代替 has_and_belongs_to_many
,它允许连接表具有主键。