undefined method `enum' for #<Class:0x007f099c303390> - ruby-on-rails

I am using in rails and getting following error:
undefined method `enum' for #<Class:0x007f03202a1190
Model
class Location < ActiveRecord::Base
enum status: [ :current, :preffered ]
end
How can i remove this error.

ActiveRecord::Enum was only introduced to Rails at commit db41eb8a, and so far this commit has only been released with Rails tag v4.1.0.beta1.
It's likely that the current Rails gem you're using does not yet have this commit, and so does not have the code for implementing enum.
To check to see which version of the Rails gem you have, run:
bundle show rails
I just ran bundle update and then bundle show rails, and I am showing:
[PATH TO YOUR GEMS]/rails-4.0.2
This version of the gem does not include the code with enum. You can see this by comparing what is in v4.0.2 with what is in v4.0.1.beta1. If you click on 'File Changed' and then do a search in the page for enum.rb, you'll see that that is completely newly added code.
If you want to ensure that you get the newly tagged version of Rails, you can modify your Gemfile so that your line for including rails looks like this:
gem 'rails', :git => 'git://github.com/rails/rails.git', :tag => 'v4.1.0.beta1'
After you do a bundle update, you can see by doing a bundle show rails that you have the following rails gem:
[PATH TO YOUR GEMS]/rails-f706d5f945c5
f706d5f945c5 is the commit that was tagged for release v4.1.0.beta1.
After you get this bleeding edge version of the Rails gem, you should have access to this enum functionality.

You can use this feature by copying the code in the file rails/activerecord/lib/active_record/enum plus these lines:
module ActiveRecord
class Base
extend ActiveRecord::Enum
end
end
to your app's lib/ directory and then require-ing it in your environment.rb file. Eg.: in config/environment.rb
require 'active_record_enum'
You may refer to this code we have in production.

Related

Formtastic::UnknownInputError in ActiveAdmin::Devise::Sessions#new

Using Rails 5.0.0.beta1.
Installed Active Admin and Devise. Here is Gemfile contents:
# Backend
gem 'activeadmin', '~> 1.0.0.pre2'
# Authentication
# Master branch is added for Rails 5 support
# https://github.com/plataformatec/devise/pull/3714
gem "devise", :github => 'plataformatec/devise', :branch => 'master'
Followed instruction installation here.
rails g active_admin:install User
rake db:migrate
rake db:seed
rails server
When I'm trying to enter /admin, the following error appears:
Showing /usr/local/rvm/gems/ruby-2.2.2#mysite.com/gems/activeadmin-1.0.0.pre2/app/views/active_admin/devise/sessions/new.html.erb
where line #10 raised:
Unable to find input class Input
Extracted source (around line #332):
raise Formtastic::UnknownInputError, "Unable to find input #{$!.message}"
If we look at activeadmin-1.0.0.pre2/app/views/active_admin/devise/sessions/new.html.erb (line #10), nothing special is here:
f.input :password, label: t('active_admin.devise.password.title')
What's wrong? Maybe Formtastic classes are not autoloaded for some reason? I tried to update Formtastic to the latest version, but error still remains.
I understand that using beta is kind of risky, but I want to try this out.
Figured it out. Here are the available options:
1) Probably the best option. Just use Rails 4.2.5 and wait for stable release of Rails 5 and according gem updates.
2) Create the file app/active_admin/inputs/input.rb with the following contents:
module ActiveAdmin
module Inputs
class Input < ::Formtastic::Inputs::StringInput
end
end
end
Related info is available here.
It solves accessing login page error, you can now successfully login and view dashboard. However, if you try to enter Users section for example, you get another error:
NoMethodError: undefined method flat_map for
#<ActionController::Parameters> from /usr/local/rvm/gems/ruby-2.2.2#mysite.com/gems/activeadmin-1.0.0.pre2/lib/active_admin/view_helpers/fields_for.rb:20:in fields_for_params
This is because ActionController::Parameters in Rails 5 no longer extends ActiveSupport::HashWithIndifferentAccess which includes Enumerable (which contains method flat_map).
But I think this is not the only one error you will struggle with.
3) This error, error mentioned in 2) and some other errors were fixed already on rails-5-spec branch in this pull request, so I switched to using it instead in Gemfile:
gem 'activeadmin', :github => 'activeadmin/activeadmin', :branch => 'rails-5-rspec'
Now the errors are gone.
Update: I choose 3rd option and it solves the problem on development server, but when I deployed application to production, error appeared again. I used the fix mentioned in 2) and now it's OK on production server too.
css master branch of formtastic in your Gemfile
gem 'formtastic', git: 'git#github.com:justinfrench/formtastic.git', :branch => 'master'
and do bundle update and restart server rails s -d

How can I automatically reload gem code on each request in development mode in Rails?

I am developing a Rails app where most of the code not specific to the app has been written inside of various gems, including some Rails engines and some 3rd party gems for which I am enhancing or fixing bugs.
gem 'mygem', path: File.expath_path('../../mygem', __FILE__)
Since a lot of the code in these gems is really part of the app, it's still changing frequently. I'd like to be able to utilize the Rails feature where code is reloaded on each request when in development (i.e. when config.cache_classes is false), but this is only done within the normal application structure by default.
How can I configure Rails to reload gem code on each request, just like with the app code?
I have found through trial and error that several steps are required, with the help of ActiveSupport.
Add activesupport as a dependency in the .gemspec files
spec.add_dependency 'activesupport'
Include ActiveSupport::Dependencies in the top-level module of your gem (this was the most elusive requirement)
require 'bundler'; Bundler.setup
require 'active_support/dependencies'
module MyGem
unloadable
include ActiveSupport::Dependencies
end
require 'my_gem/version.rb'
# etc...
Set up your gem to use autoloading. You an either manually use ruby autoload declarations to map symbols into filenames, or use the Rails-style folder-structure-to-module-hierarchy rules (see ActiveSupport #constantize)
In each module and class in your gem, add unloadable.
module MyModule
unloadable
end
In each file that depends on a module or class from the gem, including in the gem itself, declare them at the top of each file using require_dependency. Look up the path of the gem as necessary to properly resolve the paths.
require_dependency "#{Gem.loaded_specs['my_gem'].full_gem_path}/lib/my_gem/myclass"
If you get exceptions after modifying a file and making a request, check that you haven't missed a dependency.
For some interesting details see this comprehensive post on Rails (and ruby) autoloading.
The solution that I used for Rails 6, with a dedicated Zeitwerk class loader and file checker :
Add the gem to the Rails project using the path: option in Gemfile
gem 'mygem', path: 'TODO' # The root directory of the local gem
In the development.rb, setup the classloader and the file watcher
gem_path = 'TODO' # The root directory of the local gem, the same used in Gemfile
# Create a Zeitwerk class loader for each gem
gem_lib_path = gem_path.join('lib').join(gem_path.basename)
gem_loader = Zeitwerk::Registry.loader_for_gem(gem_lib_path)
gem_loader.enable_reloading
gem_loader.setup
# Create a file watcher that will reload the gem classes when a file changes
file_watcher = ActiveSupport::FileUpdateChecker.new(gem_path.glob('**/*')) do
gem_loader.reload
end
# Plug it to Rails to be executed on each request
Rails.application.reloaders << Class.new do
def initialize(file_watcher)
#file_watcher = file_watcher
end
def updated?
#file_watcher.execute_if_updated
end
end.new(file_watcher)
With this, on each request, the class loader will reload the gem classes if one of them has been modified.
For a detailed walkthrough, see my article Embed a gem in a Rails project and enable autoreload.

rails 4.0, rake db:sessions:create

Rails 3.1 suggests running
rails generate session_migration
However this generates the exact same migration as
rake db:sessions:create
but none of the commands are recognized by my setup using rails 4.0
errors are :
Could not find generator session_migration.
and
Don't know how to build task 'db:sessions:create'
respectively.
I have run:
gem install 'activerecord-session_store'
How do I make it work so that i can store a shopping cart bigger than 4kb?
The ActiveRecord session store has been extracted out of Rails into it's own gem as part of Rails move towards better modularity. You need to include the gem as shown below in your Gemfile to get access to the rake task and related functionality.
gem 'activerecord-session_store', github: 'rails/activerecord-session_store'
The gem
The Rails commit where the change happened
A bit of an explanation
See the README of the gem linked above for more instructions, but you still need run the following command after installing the gem
rails generate active_record:session_migration
and after that you need to modify the config/initializers/session_store.rb to look like something like this
MyApp::Application.config.session_store :active_record_store, :key => '_Application_session'
or
Rails.application.config.session_store :active_record_store, :key => '_Application_session'
depending on your Rails version.

uninitialized constant Delayed::Job

I've added the delayed_job gem to my gemfile and installed correctly but when I try to run the following line:
Delayed::Job.enqueue do_it(), 0, 1.minutes.from_now.getutc
I get the error 'uninitialized constant Delayed::Job'
Can somebody explain what i need to do here? I've tried running 'rake jobs:work' beforehand but it also returns the 'uninitialized constant Delayed::Job' error. Additionally, I've added "require 'delayed_job'" to the file (application.rb) without much luck.
If you've upgraded to delayed_job version >=3 you'll need to add this (presuming you're using ActiveRecord):
# Gemfile
gem 'delayed_job_active_record'
Did you follow the installation instructions on the README file? https://github.com/collectiveidea/delayed_job
Add this to your gemfile:
gem 'delayed_job_active_record'
and then run this at the console:
$ rails generate delayed_job:active_record
$ rake db:migrate
You need to create the delayed jobs table in the database (this assumes you're using active record).
For Rails 3, all you need to do is include it in the gemfile, run that code above to create the table and migrate the database, then restart your server and go!
I'm using delayed job within an engine (so the gem is specified in a .gemspec rather than Gemfile) and was getting the same error. I found that I could solve the problem by using:
require 'delayed_job_active_record' # fixes problem
rather than
require 'delayed_job' # doesn't
Just in case, if this is still unanswered, check the below link
http://www.pipetodevnull.com/past/2010/4/14/uninitialized_constant_delayedjob/
edit: Alternative, just upgrade to the latest version - 2.1
i was struggling a while back with the same problem. i was following ryan bates screencast on delayed_job and got the same error 'uninitialized constant Delayed::Job'. In the screencast ryan creates a file called mailing_job.rb(located under lib folder) with the delayed_job perform method inside, which allows you to use the enqueue method. After doing some research i found that rails 3 does not automatically load the lib folder files into your app.(not entirely sure)
Try this
In your controller where you use this:
"Delayed::Job.enqueue do_it(), 0, 1.minutes.from_now.getutc"
Try to require the file like this.
require 'mailing_job'
class AssetsController < ApplicationController
def some_method
Delayed::Job.enqueue do_it(), 0, 1.minutes.from_now.getutc
end
end
Version change possibility : if you jump from the 2.1.x to the 3.x version of the gem via a non locked down bundle, you may have a similar issue.

GEM Version Requirements Deprecated

When creating a new Rails project using:
rails sample
Then creating a model using:
script/generate model person first_name:string last_name:string
Everything is fine. However, if I add any gems to my environment.rb:
config.gem "authlogic"
And run the same generator, I get the following:
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/gem_dependency.rb:119:Warning:
Gem::Dependency#version_requirements
is deprecated and will be removed on
or after August 2010.
The warning just recently appeared (I think), but I would like to fix it if possible. Any hints or similar experiences?
Thanks.
did you try:
rake gems:install
Btw. If you are using rubygems 1.3.6 then you get this deprecation warning. Previous versions never gave a warning. Also i suggest installing any gem using the command line rather than adding it in the environment.rb file. If the gem(s) you have added in the file is/are not installed, then the generator or any rake task will simply not run. Its a minor bug.
Here is an article that describes a way to prevent the warning:
http://www.mattvsworld.com/blog/2010/03/version_requirements-deprecated-warning-in-rails/
Its no big deal though. Just install gems the normal way and don't add any to your environment.rb file. You'll never get the deprecation warning.
This may be irrelevant as it is rails 3.0 but the answer you are looking for is in this article:
http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade
down by the section titled "config.gem is dead, long live bundler", although the article does explain some new things.
You may want to consider upgrading to rails 3.0 and when you do, you will be using the Gemfile inside your application. in here, you will want to include the line:
gem 'authlogic'
and then on the command line, run
sudo bundle install
After that, all should be set :)
Check https://gist.github.com/807008 they suggest to downgrade and upgrade again rubygems.
Worked for me...
Putting these lines in your config/environment.rb between your bootstrap and your initializer will remove the deprecation warning:
if Gem::VERSION >= "1.3.6"
module Rails
class GemDependency
def requirement
super == Gem::Requirement.default ? nil : super
end
end
end
end

Resources