在 Rails 中使用联接查找范围下的 delete_all

发布于 2024-10-31 07:29:27 字数 955 浏览 0 评论 0原文

我有一个书籍模型、一个标签模型和一个称为 bookstags 的连接模型,它们如下所示。

当我想读取所有via_tags时,Book.first.via_tags它会起作用,
但是当我尝试删除所有相关的via_tags时,我尝试了Book.first.via_tags.delete_all() 我有一个例外。

ActiveRecord::StatementInvalid: SQLite3::SQLException: near "INNER": syntax error: DELETE FROM "tags" INNER JOIN "books_tags" ON "tags".id = "books_tags".tag_id WHERE (("books_tags".book_id = 25)) AND ("tags"."kind" = 0)

所以我想问的是,是否可以通过连接执行delete_all?

class Book < ActiveRecord::Base
  has_many :tags, :through =>  :books_tags
end

class BooksTags < ActiveRecord::Base
  belongs_to :book
  belongs_to :tag
  def self.with_via_tag
    find(:all, :joins => :tag, :conditions => {:tags => {:kind => Tag.kind_index(:via)}})
  end
end

class Tags
  has_many :books_tags
  has_many :books, :through => :books_tags
  @kinds = [:via,:cate,:attr]
  def self.kind_index kind
    @kinds.index(kind)
  end
end

I have a book model , a tag model and a join model called bookstags, they looks like following.

When I want to read all via_tags, Book.first.via_tags it works will,
but when I try to delete all related via_tags, I tried Book.first.via_tags.delete_all()
And I got an Exception.

ActiveRecord::StatementInvalid: SQLite3::SQLException: near "INNER": syntax error: DELETE FROM "tags" INNER JOIN "books_tags" ON "tags".id = "books_tags".tag_id WHERE (("books_tags".book_id = 25)) AND ("tags"."kind" = 0)

So I want to ask is, is it possible to perform delete_all with joins?

class Book < ActiveRecord::Base
  has_many :tags, :through =>  :books_tags
end

class BooksTags < ActiveRecord::Base
  belongs_to :book
  belongs_to :tag
  def self.with_via_tag
    find(:all, :joins => :tag, :conditions => {:tags => {:kind => Tag.kind_index(:via)}})
  end
end

class Tags
  has_many :books_tags
  has_many :books, :through => :books_tags
  @kinds = [:via,:cate,:attr]
  def self.kind_index kind
    @kinds.index(kind)
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

太阳哥哥 2024-11-07 07:29:28

不,因为 delete_all 会丢弃连接信息。请参阅此答案以了解编写查询的另一种方式:https://stackoverflow.com/a/7639857/156109

No, because delete_all discards join information. See this answer for an alternate way of writing your query: https://stackoverflow.com/a/7639857/156109

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文