我有一个书籍模型,一个标签模型和一个名为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
答案 0 :(得分:0)
不,因为delete_all
会丢弃加入信息。有关编写查询的其他方法,请参阅此答案:https://stackoverflow.com/a/7639857/156109