ohhh
ohhh

Reputation: 707

Destroying resources from outside the controller

Is it un-RESTful/un-Ruby/bad practice to destroy objects in ruby on rails by doing a ".destroy" on an active record outside it's controller? For instance, when a user is destroyed I call destroy on all their posts from the User controller.

Upvotes: 2

Views: 79

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

ActiveRecord

In reference to jkeuhlen's answer, I would not say it's outright bad practice to destroy an ActiveRecord object from a different controller, in principle.

In your case, it would not be very efficient to do it your way, but it wouldn't be against convention in my opinion:

enter image description here

As I understand, the MVC programming pattern basically means that if you call a controller, its primary function is to build a set of data depending on the users' input. This may, or may not, involve the controller's corresponding model

Although against the Resourceful principle directly, I don't see why it would be a problem to destroy data depending on various controller actions - if it doesn't involve the model, surely you'd be able to destroy all the relevant data from that controller?

--

Rails

As pointed out by jkeuhlen, Rails comes with a dependent: :destroy method to remove associative data upon record deletion.

The only thing to add to jkheuhlen's answer is as follows (taken from the answer):

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

enter image description here

This would mean that if you called the following, you need to make sure you're able to call the following:

#app/controllers/users_controller.rb
Class UsersController < ApplicationController
   def destroy
       @user = User.find params[:id]
       @user.destroy -> will destroy all associated `posts`
   end
end

Upvotes: 1

jkeuhlen
jkeuhlen

Reputation: 4517

I would say yes, it is bad practice to do this. But mostly because there is a better way that rails has implemented for you. Like MrYoshiji pointed out in his comment, you should create an association between the user and a post.

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

Then when you delete a user, rails will automagically handle the destroys of the posts.

Upvotes: 2

Related Questions