Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't delete_all associated records with "has_many through"

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!

like image 275
Parandroid Avatar asked Jun 04 '13 11:06

Parandroid


2 Answers

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

like image 197
lion.vollnhals Avatar answered Sep 20 '22 13:09

lion.vollnhals


Try:-

my_user.shedules.destroy_all

OR

Shedule.delete_all(:owner => my_user.id)
like image 20
Deepika Avatar answered Sep 23 '22 13:09

Deepika