Why use thin controller with fat model?

Reading time ~1 minute

why skinny controller, fat model?

If you try to read on the project Redmine project, for example, the activities_controller#index`,

This is the part if the index action:

   def index
      @days = Setting.activity_days_default.to_i

      if params[:from]
        begin; @date_to = params[:from].to_date + 1; rescue; end
      end

      @date_to ||= User.current.today + 1
      @date_from = @date_to - @days
      @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
      if params[:user_id].present?
        @author = User.active.find(params[:user_id])
      end

      @activity = Redmine::Activity::Fetcher.new(User.current, :project => @project,
                                                               :with_subprojects => @with_subprojects,
                                                               :author => @author)
      pref = User.current.pref
      @activity.scope_select {|t| !params["show_#{t}"].nil?}
      if @activity.scope.present?
        if params[:submit].present?
          pref.activity_scope = @activity.scope
          pref.save
        end
      else
      end
  #....
  end

If the controllers is too fat:

  • difficult to understand
  • difficult for team member who just joins the project

you can pull out the business logic to the model

When I see people’s code, the first thing that I want to check is the controller, I want to see if there are lots of business logic in it.

The good part to be the fat model:

  • easy to read
  • easy to maintain
  • if you put them into different model, you can test them seperately, and grow the complexity easily better than everything tangle in the controller.

to_param in Ruby on Rails

If I want a custom slug=======================I walk through this cutstom slug.1. create migration `add_slug` to add a column inside the...… Continue reading

What is ORM in Rails mean?

Published on July 14, 2017