I have just started working with rails and I encountered this error which does not give a lot of detail. Since I am not familiar with ruby on rails, perhaps someone here can help.
The error occurs in the active model serializer for the model.
class SecuritySerializer < ActiveModel::Serializer
attributes :id, :name, :ticker, :identifier, :weight
end
the rendering occurs as follows:
def index
#securities = Security.all
render(json: #securities, each_serializer: SecuritySerializer)
end
The error that I get:
Errno::ENOENT (No such file or directory # rb_sysopen - C):
app/serializers/security_serializer.rb:1:in `<top (required)>'
app/controllers/securities_controller.rb:9:in `index'
EDIT
I am using 64-bit ruby on windows 8.
I added this to a file called serializer_init.rb in config/initializers
ActiveModel::Serializer.config.adapter = :json_api
I was using version 0.10.0. I downgraded to 0.8.0 and removed the initializer. This solved the issue.
User gem from branch master.
gem 'active_model_serializers', :git => 'git://github.com/rails-api/active_model_serializers.git'
Related
I am in the process of upgrading a ~2 year old Rails app from 6.1 to 7.0.1
I have an STI setup where Pursuit is the main class and it has several other types as descendants:
# app/models/pursuit.rb
require 'sti_preload'
class Pursuit < ApplicationRecord
# ...
end
Descendant classes all look like this:
# app/models/pur_issue.rb
class PurIssue < Pursuit
# ...
end
--
# app/models/pur_goal.rb
class PurGoal < Pursuit
# ...
end
--
# app/models/pur_tracker.rb
class PurTracker < Pursuit
# ...
end
I have been using STI preload snippet as recommended by the Ruby Guides, and all worked well under Rails 6.0 and 6.1.
But now that I am upgrading to Rails 7.0.1, I suddenly get an "Uninitialized Constant" error for only the PurIssue subclass whereas all the other subclasses load fine:
Showing /Users/me/gits/rffvp/app/views/pursuits/_stats.html.slim where line #1 raised:
uninitialized constant PurIssue
Extracted source (around line #33):
33 types_in_db.each do |type|
34 logger.debug("Preloading STI type #{type}")
35 type.constantize
36 end
37 logger.debug("Types in database #{types_in_db}")
Trace of template inclusion: #<ActionView::Template app/views/layouts/_footer.html.slim locals=[]>, #<ActionView::Template app/views/layouts/application.html.slim locals=[]>
Rails.root: /Users/me/gits/rffvp
Application Trace | Framework Trace | Full Trace
lib/sti_preload.rb:33:in `block in preload_sti'
lib/sti_preload.rb:31:in `each'
lib/sti_preload.rb:31:in `preload_sti'
lib/sti_preload.rb:13:in `descendants'
app/models/pursuit.rb:71:in `<class:Pursuit>'
app/models/pursuit.rb:54:in `<main>'
app/models/pur_issue.rb:52:in `<main>'
app/views/pursuits/_stats.html.slim:1
app/views/layouts/_footer.html.slim:14
app/views/layouts/application.html.slim:13
I can't seem to figure out why PurIssue will not load anymore whereas all the other subclasses will. This is breaking my entire app since PurIssues are the most important data points.
Can someone point me to a Rails configuration change between 6.0, 6.1 and 7.0 that might cause this different behavior?
# lib/sti_preload.rb
module StiPreload
unless Rails.application.config.eager_load
extend ActiveSupport::Concern
included do
cattr_accessor :preloaded, instance_accessor: false
end
class_methods do
def descendants
preload_sti unless preloaded
super
end
# Constantizes all types present in the database. There might be more on
# disk, but that does not matter in practice as far as the STI API is
# concerned.
#
# Assumes store_full_sti_class is true, the default.
def preload_sti
types_in_db = \
base_class
.unscoped
.select(inheritance_column)
.distinct
.pluck(inheritance_column)
.compact
types_in_db.each do |type|
logger.debug("Preloading STI type #{type}")
type.constantize
end
logger.debug("Types in database #{types_in_db}")
self.preloaded = true
end
end
end
end
Zeitwerk shows the same error by the way:
$ rails zeitwerk:check
Hold on, I am eager loading the application.
rails aborted!
NameError: uninitialized constant PurIssue
/Users/me/gits/rffvp/lib/sti_preload.rb:33:in `block in preload_sti'
/Users/me/gits/rffvp/lib/sti_preload.rb:31:in `each'
/Users/me/gits/rffvp/lib/sti_preload.rb:31:in `preload_sti'
/Users/me/gits/rffvp/lib/sti_preload.rb:13:in `descendants'
/Users/me/gits/rffvp/app/models/concerns/validateable.rb:10:in `block in <module:Validateable>'
/Users/me/gits/rffvp/app/models/pursuit.rb:68:in `include'
/Users/me/gits/rffvp/app/models/pursuit.rb:68:in `<class:Pursuit>'
/Users/me/gits/rffvp/app/models/pursuit.rb:54:in `<main>'
/Users/me/gits/rffvp/app/models/pur_issue.rb:1:in `<main>'
Tasks: TOP => zeitwerk:check
(See full trace by running task with --trace)
I saw the same thing trying to do an upgrade to rails 7. I believe it originates with this change: https://github.com/rails/rails/commit/ffae3bd8d69f9ed1ae185e960d7a38ec17118a4d
Effectively the change to invoke Class.descendants directly in the internal association callback methods exposes a more longstanding implicit issue with invoking Class.descendants at all during the autoload, as the StiPreload implementation may result in a problem where it circularly attempts to constantize the original class being autoloaded. I've added an issue in the Rails repo here https://github.com/rails/rails/issues/44252
The following spec passes fine in Ruby 2.1.5 but fails in 2.2.0 and I can't tell what that's all about:
# job.rb
class Job < ActiveRecord::Base
validates :link, :url => true
end
# job_spec.rb
require 'rails_helper'
describe Job do
describe "#create" do
["blah", "http://", " "].each do |bad_link|
it {
should_not allow_value(bad_link).for(:link)
}
end
end
end
fail log looks like this:
1) Job#create should not allow link to be set to "http://"
Failure/Error: should_not allow_value(bad_link).for(:link)
Expected errors when link is set to "http://",
got no errors
# ./spec/models/job_spec.rb:14:in `block (4 levels) in <top (required)>'
I find the only way to for that spec to pass with Ruby 2.2.0 is to include the validates_url gem in my project!!
Does anyone know this is about?
Maybe my solution isn't ideal, but it works.
Replace validates_url gem by validates gem. It has UrlValidator (written by me), which is well tested.
gem 'validates' # in Gemfile
validates :link, :url => true # you needn't to change something. Just remove validates_url from your Gemfile
P.S. It's a strange way - to test functionality of gem. Functionality should be tested in gem already.
P.P.S. I'm strongly recommend you to move to ruby 2.2.1 (or 2.2.2) instead of 2.2.0, because of 2.2.0 has a lot of bugs
I just created a new app from scratch on rails4.0.0.rc1 with 1.9.3-p374 (which should work according to the guides).
However, I fail doing a simple create-action.
class Books
def create
#book = Book.new book_params
if #book.save
redirect_to #book
else
render action: :new
end
end
private
def book_params
params.require(:book).permit(:name, :description)
end
end
Doing a create here results a
undefined method `synchronize' for nil:NilClass
with the error pointing to the line of if #book.save.
Is that because of 1.9.3 or did I miss something?
Apparently, It was failing because of the friendlyId gem. If you use friendlyId, you may need to specify the rails4-branch.
gem 'friendly_id', github: 'FriendlyId/friendly_id', branch: 'rails4'
edit: Make sure to get the actual branch/version from norman/friendly_id. According to the readme, it needs to be at least branch: 5.0.0-beta to work with rails4.
edit2: now it is 5.0.0.rc2, as I said, make sure to get the actual branch/version, I won't obviously update this answer every time there is a version update. Also, read the comments to this answer, there are plenty of helpful information.
pduersteler's answer didn't work for me and failed with this error:
fatal: ambiguous argument 'rails4': unknown revision or path not in the working tree.
The README was update on Sep 23, 2013 with the following, which installed without error:
gem 'friendly_id', '5.0.0.rc2' # Note: You MUST use 5.0.0 or greater for Rails 4.0+
New to Ruby on Rails and having a problem when following Michael Hartl's tutorial.I'm using Rails 3.2.2 with Ruby 1.9.3. The issue looks very similar to another question that was raised but was unanswered:
Rails Error NoMethodError in UsersController#show error
I get the following error when attempting to add a new user via /signup
Gem::LoadError in UsersController#new
bcrypt-ruby is not part of the bundle. Add it to Gemfile.
Reloading the page gives the error:
NoMethodError in UsersController#new
undefined method `key?' for nil:NilClass
The problem seems to be related to the inclusion of the bcrypt-ruby gem, and the usage of the has_secure_password method in user.rb . Removing the call to has_secure_password in user.rb gets rid of the error and it goes to the signup page successfully.
user.rb:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
#
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
validates :name, presence: true, length: { maximum: 50 }
valid_email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: valid_email_regex },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6}
end
users_controller.rb:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
flash[:success] = "Welcome!"
redirect_to #user
else
render 'new'
end
end
end
However, I cant find anything wrong with the inclusion of the bcrypt-ruby gem. In the Gemfile I have:
gem 'bcrypt-ruby', '3.0.1'
and the gem has also been generated in Gemfile.lock :
DEPENDENCIES
annotate (~> 2.4.1.beta)
bcrypt-ruby (= 3.0.1)
I've also added password_digest to the database via migration:
class AddPasswordDigestToUsers < ActiveRecord::Migration
def change
add_column :users, :password_digest, :string
end
end
Any ideas ?
I'm going through the same tutorial and encountered the exact same problem.
My solution was to restart the web server. After installing the gem, I think the web server needs to be restarted so it is loaded.
Justin
Did you tried the 'bundle update' command, usually the bundler will take care of gems if you specified in the Gemfile. If you want to check the gem dependency please check http://rubygems.org/gems.
And if you are using windows(I know its strange- but some of our app works in windows only) there is some tricks to install bcrypt
Steps to install bcrypt.
1 Download Devkit and extract
you can download it from here http://rubyinstaller.org/downloads/
2 Place devkit it your jruby folder (in my case C:\applications\jruby\devkit)
3 You need to install ruby as well either 1.8.7 or 1.9(some times needs a system restart)
4 CD into devkit directory
5 Run ruby dk.rb init
6 Open config.yml and make sure that both your jruby installtion is listed. If not, ADD them. Save and close config.yml after you're done.
example:- C:/applications/jruby
7 Run ruby dk.rb install
8 jruby -S gem install bcrypt-ruby
Restarting the web server fixed it for me (had spork running in the background to speed up the running of the tests)
I attempted to install the gmaps4rails gem.
I added gem 'gmaps4rails' to my Gemfile, and ran 'bundle install. It said that my bundle installed successfully. I can find "Using gmaps4rails (0.8.8)" with 'gem list'. I added the specified columns to my users table with rake db:migrate and added acts_as_gmappable and the gmaps4rails_address method to my User model.
Visiting pages that involve the user model gives me "undefined local variable or method 'acts_as_gmappable'"error.
Is there something that I am missing?
For greater context, the code I am using is from the Rails 3 Tutorial.
OS X 10.6.6
ruby 1.8.7
rails 3.0.7
passenger 3.0.7
Restarting the server should resolve the problem :)
I had the same issue : undefined local variable or method 'acts_as_gmappable'
I just restarted the server and it error went away.
I was using Mongoid and had the same trouble.
In which case, make sure your model includes:
include Gmaps4rails::ActsAsGmappable
acts_as_gmappable :position => :location
field :gmaps, :type => Boolean
field :location, :type => Array
def gmaps4rails_address
#describe how to retrieve the address from your model, if you use directly a db column, you can dry your code, see wiki
"#{self.address}, #{self.city}, #{self.country}"
end
I think this may be helpful (similar issue):
rvm + rails3 + gmaps4rails - acts_as_gmappable