2

Is it possible to share constants between controller and model?

e.g. in product.rb I have

PRODUCT_TYPES = %w[one two]

I want PRODUCT_TYPES constant to be available in the controllers as well.

Simone Carletti
  • 168,884
  • 43
  • 353
  • 360
Ilya Cherevkov
  • 1,713
  • 2
  • 17
  • 44

3 Answers3

6

As per my consideration your Product model looks like

 class Product < ActiveRecord::Base
      PRODUCT_TYPES = %w[one two]
 end

You can access the given constant in the controller as below

p.product_type == Product::PRODUCT_TYPES[:one]
shrikant1712
  • 4,066
  • 22
  • 39
3

I deeply explained the various possibility in this answer

You basically have 3 possibilities:

  • global scope (initializer)
  • application scope (using the application module created by Rails)
  • class scope (defined them where you want, and call them with Class::CONSTANT)
Community
  • 1
  • 1
Simone Carletti
  • 168,884
  • 43
  • 353
  • 360
0

We can access model constant in Controller as bellow...

class Invoice < ActiveRecord::Base
       STATUS_PAYABLE          = %w(APPROVED OPEN)
 end

Controller use like ..

 Invoice::STATUS_PAYABLE.include?('OPEN')
Dinesh Vaitage
  • 2,733
  • 16
  • 15