Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper methods for models in Rails

Is there a proper place for helper methods for models in Rails? There are helper methods for controllers and views, but I'm not sure where the best place to put model helper methods. Aside from adding a method to ActiveRecord::Base, which I'd prefer not to.

UPDATE: It seems Concerns make a lot of sense. Here's an example of what I want. Certain models can never be deleted, so I add a callback that always throws an exception:

before_destroy :nope
def nope
  raise 'Deleting not allowed'
end

With concerns, I could do something like this?

class MyModel < ActiveRecord::Base
  include Undeletable
end

module Undeletable
    extend ActiveSupport::Concern

    included do 
      before_destroy :nope 
    end

    def nope
      raise 'Deleting not allowed'
    end
end

Is this the Rails way of doing this?

like image 949
at. Avatar asked Mar 19 '15 09:03

at.


People also ask

What are helper methods in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

What are helper methods?

A helper method is a term used to describe some method that is reused often by other methods or parts of a program. Helper methods are typically not too complex and help shorten code for frequently used minor tasks. Using helper methods can also help to reduce error in code by having the logic in one place.

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.


1 Answers

If what you are asking is where to put code that is shared across multiple models in rails 4.2, then the standard answer has to be to use Concerns: How to use concerns in Rails 4

However, there are some good arguments (e.g. this) to just using standard rails module includes, and extends as marek-lipka suggests.

I would strongly recommend NOT using ApplicationController helper methods in a model, as you'll be importing a lot unnecessary baggage along with it. Doing so is usually a bad smell in my opinion, as it means you are not separating the MVC elements, and there is too much interdependency in your app.

If you need to modify a model object by adding a method that is just used within a view, then have a look at decorators. For example https://github.com/drapergem/draper

like image 192
11 revs, 10 users 40% Avatar answered Sep 18 '22 13:09

11 revs, 10 users 40%