在 Rails 中使用联接查找范围下的 delete_all
我有一个书籍模型、一个标签模型和一个称为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,因为
delete_all
会丢弃连接信息。请参阅此答案以了解编写查询的另一种方式:https://stackoverflow.com/a/7639857/156109No, because
delete_all
discards join information. See this answer for an alternate way of writing your query: https://stackoverflow.com/a/7639857/156109