Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ApplicationHelper from User.rb model

Here's some simple code that isn't working:

module ApplicationHelper
  def industries
    industries = ['Agriculture','Food', etc.]
  end
end

class User < ActiveRecord::Base
  include ApplicationHelper
  validates_inclusion_of :industries, :in => ApplicationHelper.industries
  ...
end

This code is failing when a user action is run with undefined method 'industries'. Do you know how I can reference the helper (or preferably just industries) the right way?


Edit

Based on the code in Mauricio's answer below, how can INDUSTRIES be accessed in a controller and a view? I'm having real trouble making industries accessible everywhere, but it really needs to be for my application.

like image 753
sscirrus Avatar asked Dec 01 '25 10:12

sscirrus


1 Answers

You should never do something like this. ApplicationHelper is not supposed to be included in a model. Best solution would be:

class User < ActiveRecord::Base
    INDUSTRIES = ['Agriculture','Food']
    validates_inclusion_of :industries, :in => INDUSTRIES
end

module ApplicationHelper
    def industries
        User::INDUSTRIES
    end
end

And now you have it done in a simple and nice way.

EDIT

Anywhere you need to access industries you should use:

User::INDUSTRIES

And that's it.

like image 106
Maurício Linhares Avatar answered Dec 04 '25 01:12

Maurício Linhares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!