我有一个book模型,一个标签模型和一个名为bookstags的连接模型,它们看起来如下:
当我想要读取所有的via_tags时,Book.first。Via_tags它将工作,
但是当我尝试删除所有相关的via_tags时,我尝试了Book.first.via_tags.delete_all()我得到了一个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)
所以我想问的是,是否有可能执行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
不存在,因为delete_all
丢弃了连接信息。请参阅此答案,了解编写查询的另一种方式:https://stackoverflow.com/a/7639857/156109