我有三個型號無法通過
主題
class Subject < ActiveRecord::Base
has_many :enrollments, dependent: :destroy
has_many :students, through: :enrollments, source: :students
用戶
class User < ActiveRecord::Base
has_many :enrollments, foreign_key: 'student_id', dependent: :destroy
has_many :subjects, through: :enrollments
招生
class Enrollment < ActiveRecord::Base
belongs_to :subject
belongs_to :student, class_name 'User'
讓我們說,首先我做
刪除的has_manyUser.count # return 23
它返回23,這很好。但是,如果我做
c = Subject.first # Any subject
s = c.students
s.size # It returns 1, so it does have AR, and I can see the users.
s.class # For some reason it is an Array, not an AR, but rails is probably lying
s.destroy_all # Shows it destroys it successfully
s # Returns []
c.students # Returns []
但問題是,當我打電話
User.count # It still return 23
計數是錯誤的。它應該是22.我仍然可以使用User.find(delete_student_id) 仍然可以看到記錄。當我使用User.count時,這不是一個緩存問題,因爲我使用User.all.size,它給出了23.
我想讓學生實際上從數據庫中刪除,使用subject.students.destroy_all
現在我使用
User.where(id: s.pluck('users.id')).destroy_all
或
s.each do |student|
student.destroy
end
那些將工作,但一個大碼的氣味給我。
s是用戶/學生的數組,你是什麼意思? – sonnyhe2002
[destroy_all的文檔](http://apidock.com/rails/v3.2.13/ActiveRecord/Associations/CollectionAssociation/destroy_all)(或[destroy_all](http://apidock.com/rails/v3.2.13/ActiveRecord/Relation/destroy_all))在@ sonnyhe2002的一面。由於代碼片段非常短,所以我最好的選擇是[事務](http://apidock.com/rails/v3.2.13/ActiveRecord/Transactions/ClassMethods),以防止更改被保留。 – TheConstructor