I have an action called update_mobile and in it I am preparing a massive amount of instance variables that I use in a RABL JSON request. You can see that if the request contains the params[:last_updated] parameter, then I only get the models that have been updated since then. This seems to disobey the “Fat Models, Skinny Controllers” method. How can I refactor this method?
def update_mobile
@last_updated = params[:last_updated]
if @last_updated.nil?
@buddies = @user.friends
@courses = @user.courses
@friendly_schools = @user.friendly_schools
@documents = @user.all_notes
@instructors = @user.current_instructors
@friendships = @user.friendships
@questions = @user.current_questions
@answers = @user.current_answers
@comments = @user.current_comments
else
@buddies = @user.friends.select{ |user| user.updated_at > @last_updated }
@courses = @user.courses.select{ |course| course.updated_at > @last_updated }
@friendly_schools = @user.friendly_schools.select{ |school| school.updated_at > @last_updated }
@documents = @user.all_notes.select{ |note| note.updated_at > @last_updated }
@instructors = @user.current_instructors.select{ |instructor| instructor.updated_at > @last_updated }
@friendships = @user.friendships.select{ |friendship| friendship.updated_at > @last_updated }
@questions = @user.current_questions.select{ |question| question.updated_at > @last_updated }
@answers = @user.current_answers.select{ |answer| answer.updated_at > @last_updated }
@comments = @user.current_comments.select{ |comment| comment.updated_at > @last_updated }
end
end
You should move the code out to your model and let your model deal with 1) the parameter being
niland 2) using ActiveRecord to query the database effectively.In your controller, have lines like this for each of your variables:
(I’ve renamed
@buddieshere to@friends, because we want to maintain consistency in naming the things of the system)Then, in your
Friendmodel, define a class method calledupdated_sincethat does that logic: