cjm2671
cjm2671

Reputation: 19476

Helpers vs controllers in Rails

I want to add a function to my User object, so I was going to create a user controller to do this (I'm using Devise so I believe this should add a function to the existing Devise user object). I noticed there's a folder called 'helpers' in my rails project, should I be putting my extra functions in there instead of inside the controller? The method is to enable anonymous sessions, something that doesn't come out of the box with devise.

Upvotes: 0

Views: 577

Answers (3)

Shanison
Shanison

Reputation: 2295

Thin Controller and Fat Models. Try to follow this principle when creating rails application. put your logic and some calculations if needed in Models. Controllers is used to controller what data to pass to views and how to display data. Put only those methods that helps your display of views in Helpers. e.g. put the code for formating numbers inside helpers. If you want to share some source code between controllers and doesn't fit into models, then you can create a library.

Upvotes: 4

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47933

If you want to add a method to the User class, no, add it to the user.rb file:

class User < ActiveRecord::Base

 def full_name
    # logic
 end

end

If you want a method that can be used inside your controllers and views, then define a helper inside the helpers directory and add it there.

Upvotes: 2

Thomas Li
Thomas Li

Reputation: 3338

A thin controller is always better. So yes, put anything that "helps" your controller/view in the helper folder.

Upvotes: 1

Related Questions