2

I have this method which is used in many models.

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def human_to_number(human)

I wish to call this method from a controller, which doesn't use a model. How?

class StripesController < ApplicationController
  def create
    @amount = params[:amount]
    @amount = ApplicationRecord.human_to_number(@amount)

I tried to define it with self. but that made all other calls in all models broken.

I tried to include ApplicationRecord in the controller, but it complained that it needed a module, not a class.

Rails 5.0.6

Chloe
  • 25,162
  • 40
  • 190
  • 357
  • try to add this method in concern instead of ApplicationRecord – Vishal Jan 09 '18 at 04:19
  • [OK but there are model concerns, and controller concerns](https://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4). I don't see how that would help me any. – Chloe Jan 09 '18 at 04:32
  • create one concern under controller/concern like common.rb in than file define method you want use , than simply import that concern to your controller. all methods of concern will be available for your controller – Vishal Jan 09 '18 at 04:57
  • Add `human_to_number(amount)` method to your concern. and call it from your controller. Services is also great option . i can make you service if you give me full code what you want – Vishal Jan 09 '18 at 04:58
  • If I make a controller concern, how will the models use it? Of course I can just copy & paste the code into all the files, but I'm trying to structure it so I don't have to repeat the code in multiple places! – Chloe Jan 09 '18 at 16:58
  • You can create service for that – Vishal Jan 09 '18 at 17:14

1 Answers1

0

I solved it with

u = User.new
@amount = u.human_to_number(@amount)

But this solution really sucks! I hope someone can find a better way!

Chloe
  • 25,162
  • 40
  • 190
  • 357