3

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
  • 173,507
  • 49
  • 363
  • 364
Ilya Cherevkov
  • 1,743
  • 2
  • 17
  • 47

3 Answers3

9

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,336
  • 1
  • 24
  • 42
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
  • 173,507
  • 49
  • 363
  • 364
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,983
  • 19
  • 16