Search code examples
ruby-on-rails-4model-associationsdelete-record

Deleting association record in Rails


I have two models.

class User<<ActiveRecord::Base
has_many :projects
end

class Project<<ActiveRecord::Base
belongs_to :user
end

Then in console, I load a project in variable 'p' and an user in variable 'u'. Consider the following commands

u = User.first
p = Project.first
u.projects<<p

Now,

u.projects and p.user, both are showing correct amd expected output.

My question is that how can I delete project 'p' from projects of user 'u' such that result is reflected in both the models.

I have tried doing

u.projects.delete(p)

This only removes 'p' from projects of 'u'

but p.user still shows 'u' which I don't want. So, how I can I manage this?


Solution

  • Doing a reload operation using u.reload solved my problems. Thanks to mr_sudaca for suggesting. Reload operation fetches the latest state of records from db and refreshes the objects stored in memory to reflect latest state of objects.