How do you decide that a line of code must be moved from controller to model?
I've done some research already about this best practice and here's the best explanations so far, but I hope you guys can expand this well because my newbie brain can't fully comprehend it :)
- any non-response-related logic should go in the model
- you only need process request parameters and initialize model layer in controllers
- Business logic need to be implemented in model layer
EDIT: Let's say I want to refactor my controller below from:
class TaskController < ApplicationController
def index
@tasks = Task.find_all_by_complete(:false, :order => "created_at DESC")
end
end
to
class TaskController < ApplicationController
def index
@tasks = Task.find_incomplete
end
end
Which of these 2 code blocks are correct?
class Task < ActiveRecord::Base
def self.find_incomplete
find_all_by_complete(:false, :order => "created_at DESC")
end
end
or
class Task < ActiveRecord::Base
def find_incomplete
self.find_all_by_complete(:false, :order => "created_at DESC")
end
end
EDIT2: If I want to refactor my controller below from:
@average_review = @surf_school.surf_school_reviews.average(:rating).round(2)
to
@average_review = @surf_school.average_review
my code inside model should be:
def average_review
self.surf_school_reviews.average(:rating).round(2)
end