Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Helpers vs Model

I'm new to Rails and just wondering when I should put code into a Helper as opposed to putting the code into the Model.

Is there a 'rule of thumb' so to speak for this?

like image 975
curv Avatar asked Feb 16 '11 17:02

curv


People also ask

When should you use helpers Rails?

Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better. I've seen two benefits for using helpers in my experience so far: Extract some complexity out of the view. Make view logic easier to test.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.


3 Answers

Use helpers if you're working in a view (template) and you need to build a complex bit of HTML such as a <table>. Or, if you want to change some presentation data that's not connected to the database.

def truncate_html( html, options = {} )
  options[:length] = 35 unless options[:length]
  truncate( strip_tags( html ), options )
end

Use models when you're working with database objects, and you want to simplify the business logic.

  def one_day?
    start_date.to_s[0,9] == end_date.to_s[0,9]
  end  

Here's Helpers in the guides: http://guides.rubyonrails.org/form_helpers.html

And here's Models: http://guides.rubyonrails.org/active_record_querying.html

like image 172
Chuck Bergeron Avatar answered Oct 19 '22 08:10

Chuck Bergeron


It's best to use helpers when the code that the helper is creating is meant to be displayed in the view only. For example if you want to have methods that help create HTML links, they should go in the helper:

def easy_link user
  link_to(user.name, user)
end

If your code is business logic it should go in your models. You should also aim to put as much business logic in your models, you don't want this code in your views and controllers. For example, if you want to process an order, that code should go in the model:

def process
  raise NotReadyToProcess unless ready_to_process?
  raise NotValidPaymentDetails unless valid_payment_details?
  process_payment
end
like image 21
Pan Thomakos Avatar answered Oct 19 '22 07:10

Pan Thomakos


Helpers should only contain logic for the view

Models should contain only logic related to the object modeled, never related with the transaction performed neither the view rendered

like image 4
Fernando Diaz Garrido Avatar answered Oct 19 '22 08:10

Fernando Diaz Garrido