Relationships and delete

hello

I have a cars table and photos table. One car can have many photos, i
specified the relationships, everything seems to work. Why if i destroy
the car object, it doesnt destroy all the images of that car in the
photos table? is it possible or i have to write a seprate line to take
care of that?

You need to tell the relationship that the photo’s are dependent on the
car. So…

has_many :photos, :dependent => :destroy

Now, when you destroy the car, all it’s photos go with it. See the API
for more info…

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000530

I have a cars table and photos table. One car can have many photos, i
specified the relationships, everything seems to work. Why if i destroy
the car object, it doesnt destroy all the images of that car in the
photos table? is it possible or i have to write a seprate line to take
care of that?

In your model’s :has_many, add this:

:dependent - if set to :destroy all the associated objects are destroyed
alongside this object by calling their destroy method. If set to
:delete_all all associated objects are deleted without calling their
destroy method. If set to :nullify all associated objects. foreign keys
are set to NULL without calling their save callbacks. NOTE: :dependent
=>
true is deprecated and has been replaced with :dependent => :destroy.
May
not be set if :exclusively_dependent is also set.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000530

Jon G. wrote:

You need to tell the relationship that the photo’s are dependent on the
car. So…

has_many :photos, :dependent => :destroy

Now, when you destroy the car, all it’s photos go with it. See the API
for more info…

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000530

aaaa…so simple…thanks!!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs