I have 3 models:
Shedule
belongs_to :service
Service
belongs_to :user, :foreign_key => "owner"
has_many :shedules, :dependent => :destroy
User
has_many :services, :foreign_key => "owner", :dependent => :destroy
has_many :shedules, :through => :services, :foreign_key => "owner", :dependent => :destroy
Then i can see all shedules of user by my_user.shedules
My goal is deleting all shedules of user, then i try my_user.shedules.delete_all
but get this error:
ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'User#shedules' because the source reflection class 'Shedule' is associated to 'Service' via :has_many.
After some googling i find this and some other similar posts, but all of them dont fit to my problem.
Of course i can delete this by iterating the user services like
my_user.services.each do |s|
s.shedules.delete_all
end
But i'm interesting why my_user.shedules.delete_all
dont't work.
Thanks!
Found an easier solution than presented here before.
Schedule.merge(my_user.schedules).delete_all
I prefer this because it is only one database query and I do not have to remember what the foreign key is named.
It works because:
Schedule.merge(my_user.schedules).to_sql == my_user.schedules.to_sql
Try:-
my_user.shedules.destroy_all
OR
Shedule.delete_all(:owner => my_user.id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With