Question

I am trying to set a default value on an attribute by pointing to a Module constant, but things are not going to plan. Relevant code includes:

[lib/establishments.rb]
module Establishments
  BAR = "Bar"
  RESTAURANT = "Restaurant"
  BENEFIT = "Benefit"
end

[20140321164012_add_type_to_discount]
include Establishments
class AddTypeToDiscount < ActiveRecord::Migration

  def change
    add_column :discounts, :type, :string, :default => Establishments::RESTAURANT
  end
end

rake db:migrate

Above code results in:

rake aborted!
An error has occurred, this and all later migrations canceled:

uninitialized constant Establishments/home/bob/Dev/app/db/migrate/20140321164012_add_type_to_discount.rb:1:in `<top (required)>'

Looks to me that the /lib path is not being picked up by rake. I'm not sure how to influence that.

I have also tried adding:

require 'lib/establishments.rb'

To the top of the migration file, but that complains of no such file.

Was it helpful?

Solution

Try with:

require "#{Rails.root}/lib/establishments"

Then you are able to use Establishments::RESTAURANT

OTHER TIPS

Use require_relative '../../lib/establishments' instead of include Establishments

Thanks for the answers, all valid - just as I found (equally valid)

require File.expand_path('lib/establishments')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top