jenson-button-event
jenson-button-event

Reputation: 18951

Error referencing module constants as a :default in an ActiveRecord::Migration

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.

Upvotes: 1

Views: 63

Answers (3)

jenson-button-event
jenson-button-event

Reputation: 18951

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

require File.expand_path('lib/establishments')

Upvotes: 1

Kirti Thorat
Kirti Thorat

Reputation: 53038

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

Upvotes: 1

markets
markets

Reputation: 7033

Try with:

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

Then you are able to use Establishments::RESTAURANT

Upvotes: 2

Related Questions