By

Ruby on Rails Controller VS. Model

This post is migrated from this Stack Overflow question

Often times the question comes up in Rails regarding what code belongs in the model vs the controller. Picture this, the web request comes into the controller, and from there we access the model, and then back into the controller. So to answer this question I would say that any code that can be used in multiple controllers should be moved to functions inside of a model.

Take the following example

@user = User.find(params[:id])
@stripe_cards = Stripe::Customer.retreive(@user.stripe_customer_id).cards.all

Since I'm fairly confident that we're going to want to use this feature of accessing the stripe customer of the user, I would define a method in the user model.

class User.rb
  def customer
    Stripe::Customer.retreive(self.stripe_customer_id).cards.all
  end
end

The bottom line is, controllers should be used to find records and authrrize actions. Any time code can be reused in multiple controllers, move it to a model.

Written by
Programmer, Entrepreneur, Startup Enthusiast