Dependent Vs Through And Delete Vs. Destroy In Ruby On Rails

An user has many realtors and a realtor has many messages. The realtors are also dependent upon the user and the messages are dependent upon the realtor.
In Ruby code this looks like:

User.rb Model

class User < ActiveRecord::Base
has_many :realtors, :dependent => :destroy
has_many :messages, :through => :realtors
end


and now Realtor.rb Model

class Realtor < ActiveRecord::Base
belongs_to :user
has_many :messages, :dependent => :destroy
end


The idea here is that when I delete an User, I also delete any associated realtors and any associated messages. My controller looked like this:

def delete
User.delete(params[:id])
end


The delete method essentially deletes a row (or an array of rows) from the database. Destroy on the other hand allows for a few more options. First, it will check any callbacks such as before_delete, or any dependencies that we specify in our model. Next, it will keep the object that just got deleted in memory; this allows us to leave a message saying something like “User #{user.id} has been deleted.” Lastly, and most importantly, it will also delete any child objects associated with that object!

Now my code in my controller looks like this.

def destroy
User.destroy(params[:id])
end

Whenever I delete an user object, it will delete all child realtors and message rows in the database . This prevents any orphaned rows and allows for consistency in the database!

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleteing nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

0 comments:

My Instagram