Redis -- undefined method `SMEMBERS' for nil:NilClass - ruby-on-rails

I'm building a Rails shopping cart app using Redis. Everything works fine until I try to view my cart, at which point I get this error.
NoMethodError in CartsController#show
undefined method `SMEMBERS' for nil:NilClass
Extracted source (around line #6):
5 def show
6 cart_ids = $redis.SMEMBERS current_user_cart
7 #order_items = current_order.order_items
8 end
The beginning of the full trace:
app/controllers/carts_controller.rb:6:in `show'
actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.2.0) lib/abstract_controller/base.rb:198:in `process_action'
actionpack (4.2.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `call'
...and thence through a bunch more behind-the-scenes stuff I haven't touched, mostly activesupport, activerecord, and railties.
Redis-server is installed and responsive; I have tested it with redis-cli.
Config/initializers/redis.rb:
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:url => uri)
App/controllers/carts_controller.rb:
class CartsController < ApplicationController
before_action :authenticate_user!
def show
cart_ids = $redis.SMEMBERS current_user_cart
#order_items = current_order.order_items
end
def add
$redis.SADD current_user_cart, params[:product_id]
render json: current_user.cart_count, status: 200
end
def remove
$redis.SREM current_user_cart, params[:product_id]
render json: current_user.cart_count, status: 200
end
private
def current_user_cart
"cart#{current_user.id}"
end
end
The worst part is that I had this problem last week, fixed it, and neglected to write down what the fix was! Anybody have any leads?

You are using uninitialized global variable $redis (look at your initializers/redis.rb where you declared constant REDIS but not $redis)
Ruby is case-sensitive language, the SMEMBERS and smembers are two different methods. So, I think you should use smembers method.

Turned out I had two versions of redis installed. I don't know if that was causing the problem, but when I uninstalled both and reinstalled the gem, the problem disappeared!

Related

Im having trouble with an name error in Ruby on rails. Getting uninitialized constant User::Authors

The following question is within Rails. When i go to localhost:3000/Api/v1/users, i get a Name error. uninitialized constant User::Authors. I can't find what the error is about. its pointing to my Users controller, index. As i will show below.
Error:
NameError in Api::V1::UsersController#index
uninitialized constant User::Authors
Extracted source (around line #8):
6 #users = User.all
7
8 render json: #users
9 end
10
11
# # GET /users/1
So as I will show below, this error doesn't make sense to me. I just dont see where its coming from:
My users controller:
class Api::V1::UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
# # GET /users
def index
#users = User.all
render json: #users
end
# # GET /users/1
def show
render json: #user
end
# POST /users
def create
#user = User.new(user_params)
if #user.save
render json: #user, status: :created, location: #user
else
render json: #user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if #user.update(user_params)
render json: #user
else
render json: #user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
#user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:name, :username, :password_digest)
end
end
Just in case im posting my Authors Controller as well.
Authors controller
class Api::V1::AuthorsController < ApplicationController
before_action :set_author, only: [:show, :update, :destroy]
# GET /authors
def index
#authors = Author.all
render json: #authors
end
# GET /authors/1
def show
render json: #author
end
# POST /authors
def create
#author = Author.new(author_params)
if #author.save
render json: #author, status: :created, location: #author
else
render json: #author.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /authors/1
def update
if #author.update(author_params)
render json: #author
else
render json: #author.errors, status: :unprocessable_entity
end
end
# DELETE /authors/1
def destroy
#author.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_author
#author = Author.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def author_params
params.require(:author).permit(:name)
end
end
My routes
Rails.application.routes.draw do
post "/api/v1/login", to: "sessions#create"
delete "/api/v1/logout", to: "sessions#destroy"
get "/api/v1/get_current_user", to: "sessions#get_current_user"
namespace :api do
namespace :v1 do
resources :comments
resources :genres
resources :authors
resources :books
resources :users do
resources :books, only: [:index]
end
end
end
end
If there is anything more i should show I can update the question.
Thank you in advance.
UPDATE:
I was asked to add full backtrace:
activerecord (6.0.2.1) lib/active_record/inheritance.rb:206:in `compute_type'
activerecord (6.0.2.1) lib/active_record/reflection.rb:422:in `compute_class'
activerecord (6.0.2.1) lib/active_record/reflection.rb:769:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/association.rb:137:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/collection_association.rb:35:in `reader'
activerecord (6.0.2.1) lib/active_record/associations/builder/association.rb:100:in `authors'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:397:in `read_attribute_for_serialization'
active_model_serializers (0.10.10) lib/active_model/serializer/reflection.rb:168:in `value'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:17:in `object'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:50:in `serializer_class'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:34:in `serializer'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:199:in `block (2 levels) in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `yield'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `block (2 levels) in associations'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `block in associations'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `block in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:194:in `object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:179:in `cache_read_multi'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:25:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/attributes.rb:14:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/base.rb:61:in `as_json'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:35:in `encode'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:22:in `encode'
activesupport (6.0.2.1) lib/active_support/core_ext/object/json.rb:42:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/serializable_resource.rb:10:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:71:in `block (3 levels) in notify'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:112:in `block in run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:24:in `block (3 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:81:in `block in notify_render'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:80:in `notify_render'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:23:in `block (2 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `block in tag_logger'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `tag_logger'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:22:in `block in instrument_rendering'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `instance_exec'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `block in run_callbacks'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:139:in `run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:70:in `block (2 levels) in notify'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:157:in `block in <module:Renderers>'
active_model_serializers (0.10.10) lib/action_controller/serialization.rb:72:in `block (2 levels) in <module:Serialization>'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:150:in `block in _render_to_body_with_renderer'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each_key'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:146:in `_render_to_body_with_renderer'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:142:in `render_to_body'
actionpack (6.0.2.1) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `block in ms'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `ms'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:85:in `cleanup_view_runtime'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:34:in `cleanup_view_runtime'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:43:in `render'
app/controllers/api/v1/users_controller.rb:8:in `index'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:136:in `process'
actionpack (6.0.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `each'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
rack (2.2.2) lib/rack/session/abstract/id.rb:266:in `context'
rack (2.2.2) lib/rack/session/abstract/id.rb:260:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/cookies.rb:648:in `call'
rack (2.2.2) lib/rack/etag.rb:27:in `call'
rack (2.2.2) lib/rack/conditional_get.rb:27:in `call'
rack (2.2.2) lib/rack/head.rb:12:in `call'
activerecord (6.0.2.1) lib/active_record/migration.rb:567:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.2.2) lib/rack/runtime.rb:22:in `call'
activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.2.2) lib/rack/sendfile.rb:110:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
rack-cors (1.1.1) lib/rack/cors.rb:100:in `call'
railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
puma (4.3.3) lib/puma/configuration.rb:228:in `call'
puma (4.3.3) lib/puma/server.rb:682:in `handle_request'
puma (4.3.3) lib/puma/server.rb:472:in `process_client'
puma (4.3.3) lib/puma/server.rb:328:in `block in run'
puma (4.3.3) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
ALSO MY MODELS. FOR THE MODELS IM ABOUT TO SHARE, THERE ARE MORE MODELS THAN THIS, BUT I GUESS THE RELEVANT ONES ARE USER AND AUTHER.
class User < ApplicationRecord
has_secure_password
has_many :books
has_many :authors, through: :books
has_many :genres, through: :books
has_many :comments
# has_many :comments, through: :books
validates :username, uniqueness: true
end
AND NOW FOR AUTHER
class Author < ApplicationRecord
has_many :books
has_many :genres, through: :books
end
Since it was correct, I can post it as a proper answer instead of a comment.
Since it seems like it's having problems to find the Author class, can you verify the file name of the Author class, just so it's not accidentally saved as app/models/authors.rb (plural instead of singular) or something. Also, try to explicitly say
has_many :authors, through: :books, class_name: '::Author'
in your User class, just to see if it can actually find it explicitly instead of inferred.
Just so it's known, the answer was posted in the comments by #DanneManne. Thank you!
-- Explicitly say has_many :authors, through: :books, class_name: '::Author' in your User class, just to see if it can actually find it explicitly instead of inferred.

Rails: :save returns NoMethodError

I am programming a small rails api for practice. The goal is to POST some data and then save it (after further processing) in a database. The object is being created successfuly. On the save method appears an error which I cannot explain:
NoMethodError (undefined method `[]' for nil:NilClass): app/controllers/api/v1/calculations_controller.rb:19:in `create'
It appears in the :create method (on POST):
# POST /calculations
def create
#calculation = Calculation.new(calculation_params)
if #calculation.save # <- This is line 19
render json: #calculation, status: :created, location: #calculation
else
render json: #calculation.errors, status: :unprocessable_entity
end
end
The model looks like this:
require 'digest'
class Calculation < ApplicationRecord
attr_reader :value, :hash_value, :algorithm, :timestamp
##known_algorithms = ['SHA2_256', 'SHA2_384', 'SHA2_512']
def initialize (params)
#value = params[:value]
#algorithm = params[:algorithm]
validate!
#hash_value, #timestamp = digest
end
private
def digest
case #algorithm
when 'SHA2_256'
result = Digest::SHA2.hexdigest(#value)
when 'SHA2_384'
result = Digest::SHA2.new(384).hexdigest(#value)
when 'SHA2_512'
result = Digest::SHA2.new(512).hexdigest(#value)
end
return result, DateTime.now
end
def validate!
raise ArgumentError.new('Value cannot be empty or NIL!') if #value.nil? or #value.empty?
raise ArgumentError.new('Unknown hashing algorithm!') unless ##known_algorithms.include? #algorithm
end
end
Why does the NoMethodError appear? Did I override some important part in the model class?
Full stack trace as requested:
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:424:in `clear_transaction_record_state'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:330:in `ensure in rollback_active_record_state!'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:330:in `rollback_active_record_state!'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:309:in `save'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/suppressor.rb:44:in `save'
/home/pbz/RubymineProjects/hasher_api/app/controllers/api/v1/calculations_controller.rb:20:in `create'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/abstract_controller/base.rb:194:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/rendering.rb:30:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/abstract_controller/callbacks.rb:42:in `block in process_action'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:132:in `run_callbacks'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/abstract_controller/callbacks.rb:41:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/rescue.rb:22:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `block in instrument'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `instrument'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/instrumentation.rb:32:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/railties/controller_runtime.rb:24:in `process_action'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/abstract_controller/base.rb:134:in `process'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal.rb:191:in `dispatch'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_controller/metal.rb:252:in `dispatch'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/routing/route_set.rb:34:in `serve'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/journey/router.rb:52:in `block in serve'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/journey/router.rb:35:in `each'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/journey/router.rb:35:in `serve'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/routing/route_set.rb:840:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/rack-2.0.6/lib/rack/etag.rb:25:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/rack-2.0.6/lib/rack/conditional_get.rb:38:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/rack-2.0.6/lib/rack/head.rb:12:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/activerecord-5.2.2/lib/active_record/migration.rb:559:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:98:in `run_callbacks'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/callbacks.rb:26:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/executor.rb:14:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/railties-5.2.2/lib/rails/rack/logger.rb:38:in `call_app'
/home/pbz/.gem/ruby/2.5.0/gems/railties-5.2.2/lib/rails/rack/logger.rb:26:in `block in call'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/tagged_logging.rb:71:in `block in tagged'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/tagged_logging.rb:28:in `tagged'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/tagged_logging.rb:71:in `tagged'
/home/pbz/.gem/ruby/2.5.0/gems/railties-5.2.2/lib/rails/rack/logger.rb:26:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/request_id.rb:27:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/rack-2.0.6/lib/rack/runtime.rb:22:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/activesupport-5.2.2/lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/executor.rb:14:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/actionpack-5.2.2/lib/action_dispatch/middleware/static.rb:127:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/rack-2.0.6/lib/rack/sendfile.rb:111:in `call'
/home/pbz/.gem/ruby/2.5.0/gems/railties-5.2.2/lib/rails/engine.rb:524:in `call'
/home/pbz/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/puma-3.12.0/lib/puma/configuration.rb:225:in `call'
/home/pbz/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/puma-3.12.0/lib/puma/server.rb:658:in `handle_request'
/home/pbz/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/puma-3.12.0/lib/puma/server.rb:472:in `process_client'
/home/pbz/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/puma-3.12.0/lib/puma/server.rb:332:in `block in run'
/home/pbz/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/puma-3.12.0/lib/puma/thread_pool.rb:133:in `block in spawn_thread'
Don't override initialize in the AR. It could possibly break a lot of stuff in your models.
You can use after_initialize.
The after_initialize callback will be called whenever an Active Record
object is instantiated, either by directly using new or when a record
is loaded from the database. It can be useful to avoid the need to
directly override your Active Record initialize method.
def after_initialize
# Gets called right after Calculation.new
# Do some stuff here
end
If you still want to use initialize you must do something like this:
def initialize(attributes = {})
super
self.attributes = attributes
end
I did find out (thanks to #Зелёный), that to create values for the model after creating it (new) I need to use the after_initialize callback Rails provides. Together with this comment on how to access model instance variables, I was able to achieve the functionality I wanted.
The original NoMethodError was a result of my incorrect use of the initialize method. The following code is the final result, which works with the default controller.
require 'digest'
class Calculation < ApplicationRecord
##known_algorithms = ['SHA2_256', 'SHA2_384', 'SHA2_512']
after_initialize :init
private
def init
validate!
calculate!
end
def calculate!
self.hash_value, self.timestamp = digest
end
def digest
case algorithm
when 'SHA2_256'
result = Digest::SHA2.hexdigest(value)
when 'SHA2_384'
result = Digest::SHA2.new(384).hexdigest(value)
when 'SHA2_512'
result = Digest::SHA2.new(512).hexdigest(value)
end
return result, DateTime.now
end
def validate!
raise ArgumentError.new('Value cannot be empty or NIL!') if value.nil? or value.empty?
raise ArgumentError.new('Unknown hashing algorithm!') unless ##known_algorithms.include? algorithm
end
end

Rails after_save send mail with updated columns

I am stuck in an issue, wherein I would like to send mail after the after_save callback in rails.
Below is my code snippet:
class Response < ActiveRecord::Base
after_create :pending_with
protected
def pending_with
self.approver = self.mapping.user
end
end
class ResponsesController < ApplicationController
def create
#response = current_user.responses.new(response_params)
respond_to do |format|
if #response.save
flash[:notice] = "Response has been saved successfully."
Notification.confirm_approver(#response).deliver
format.html { redirect_to dashboard_home_url }
else
flash[:error] = "There is some problem while saving the responses. Please try again."
format.html { render action: 'new' }
end
end
end
end
class Notification < ApplicationMailer
def confirm_approver(response)
#response = response
p "============"
p #response.approver.email.inspect
end
end
My issue is that, I am not getting approver. Getting error:
undefined method `approver' for nil:NilClass
When I checked the record in the database, apporver ('id') is successfully saved. Am I missing anything here?
BACKTRACE:
app/mailers/notification.rb:11:in `confirm_approver'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/abstract_controller/base.rb:189:in `process_action'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
vendor/gems/ruby/1.9.1activesupport (4.1.8) lib/active_support/callbacks.rb:82:in `run_callbacks'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/abstract_controller/callbacks.rb:19:in `process_action'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/abstract_controller/base.rb:136:in `process'
vendor/gems/ruby/1.9.1actionview (4.1.8) lib/action_view/rendering.rb:30:in `process'
vendor/gems/ruby/1.9.1actionmailer (4.1.8) lib/action_mailer/base.rb:580:in `block in process'
vendor/gems/ruby/1.9.1activesupport (4.1.8) lib/active_support/notifications.rb:159:in `block in instrument'
vendor/gems/ruby/1.9.1activesupport (4.1.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
vendor/gems/ruby/1.9.1activesupport (4.1.8) lib/active_support/notifications.rb:159:in `instrument'
vendor/gems/ruby/1.9.1actionmailer (4.1.8) lib/action_mailer/base.rb:577:in `process'
vendor/gems/ruby/1.9.1actionmailer (4.1.8) lib/action_mailer/base.rb:568:in `initialize'
vendor/gems/ruby/1.9.1actionmailer (4.1.8) lib/action_mailer/base.rb:551:in `new'
vendor/gems/ruby/1.9.1actionmailer (4.1.8) lib/action_mailer/base.rb:551:in `method_missing'
app/controllers/responses_controller.rb:23:in `block in create'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/action_controller/metal/mime_responds.rb:433:in `call'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/action_controller/metal/mime_responds.rb:433:in `retrieve_collector_from_mimes'
vendor/gems/ruby/1.9.1actionpack (4.1.8) lib/action_controller/metal/mime_responds.rb:256:in `respond_to'
app/controllers/responses_controller.rb:19:in `create'
Hi Based on #zwippie inputs, it worked. Just made little modification to it.
def create
#response = current_user.responses.new(response_params)
respond_to do |format|
if #response.save && #response.reload
Notification.confirm_approver(#response).deliver
flash[:notice] = "Response has been created successfully."
else
format.html { render action: 'new' }
end
end
end

How to pass multiple locals to a nested partial

This should be extremely straightforward and well documented, and I've done it several times, although there's something that's still killing me.
I have a structure of partials calling nested partials.
At some point one render call needs to pass an extra variable to the partial, although the rendering of the partial fails with a:
undefined local variable or method `<variable name>' for #<#<Class:....>
Here's my code for calling the render:
= f.simple_fields_for :orders do |c|
= render partial: "fields", locals: {f: c, step: f.object.step}
though this doesn't work either:
= f.simple_fields_for :orders do |c|
= render "fields", f: c, step: f.object.step
here's where the exception is raised:
f.input :quantity, input_html: {step: step}
the form_for comes from the views/lists/_form.html.haml:
= simple_form_for( #order, :html => { :multipart => true }, defaults: { input_html: { class: 'input-medium' } } ) do |f|
f is then passed to views/orders/_order_forms.html via
= render "orders/order_forms", f: f
here's the exception with trace:
ActionView::Template::Error (undefined local variable or method `step' for #<#<Class:0x007fe0479ba2b0>:0x007fe04256a930>):
application trace:
app/views/orders/_fields.html.haml:9:in `_app_views_orders__fields_html_haml___1860431911739668171_70300581339300'
app/views/orders/_order_forms.html.haml:30:in `_app_views_orders__order_forms_html_haml__2241963939037094859_70300612771460'
app/views/lists/_form.html.haml:48:in `block in _app_views_lists__form_html_haml__1669043093238943449_70300583658680'
app/views/lists/_form.html.haml:3:in `_app_views_lists__form_html_haml__1669043093238943449_70300583658680'
app/views/lists/new.html.erb:3:in `_app_views_lists_new_html_erb___1563391577928218041_70300593681100'
app/controllers/lists_controller.rb:67:in `new'
framework trace (the end of it):
actionpack (3.2.8) lib/action_view/template.rb:145:in `block in render'
activesupport (3.2.8) lib/active_support/notifications.rb:125:in `instrument'
actionpack (3.2.8) lib/action_view/template.rb:143:in `render'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:265:in `render_partial'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:238:in `block in render'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:237:in `render'
actionpack (3.2.8) lib/action_view/renderer/renderer.rb:41:in `render_partial'
actionpack (3.2.8) lib/action_view/helpers/rendering_helper.rb:27:in `render'
haml (4.0.3) lib/haml/helpers/action_view_mods.rb:10:in `block in render_with_haml'
haml (4.0.3) lib/haml/helpers.rb:89:in `non_haml'
haml (4.0.3) lib/haml/helpers/action_view_mods.rb:10:in `render_with_haml'
cocoon (1.2.0) lib/cocoon/view_helpers.rb:40:in `block in render_association'
I've had a similar issue before and I resolved it in simplifying the passing of locals.. but now I would really like to understand what's going on.
any clue?
I'm using:
ruby 2.0.0p297
rails 3.2.8
Thanks a lot in advance..
UPDATE
I have debugged my view and figured that the order_forms is being rendered twice, the first time step is not set, while in the second rendering it is set correctly.
I'm not sure why this happens, but I managed to work it around with adding the following line to my fields.html.haml.
-step = step || 1
basically I put a default value to step, in case it's not defined, so that at the first execution the rendering doesn't crash, while at the second execution it works properly.
The page looks as expected now. Although I'm thinking about the waste of resources when rendering the stuff twice.
any idea on why that happens?
After finding out that the code was run twice, I went investigating who else was running it.
and I realized that just few lines before there was the call to cocoon function link_to_add_association
of course it's not only the official render rendering the partial but also that function needs to render it.
I have added the line:
:render_options => {:locals => {:step => step }},
to my link_to_add_association function call and removed the workaround and now everything works as expected.
The more modern version analogous to this would be:
render_options: {locals: {step: step }},
a bit shorter, and looking better.

Spree - access to Order class

I have a problem with extending a spree controller. When I override the controller I cannot get access to the Order class. I get the following error (I use spree 1.2.4):
NameError (uninitialized constant Spree::Admin::OrdersController::Order):
spree_russian_post/app/controllers/admin/orders_controller_decorator.rb:9:in `sample_method'
actionpack (3.2.8) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.8) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.8) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.8) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
...
The problem is in my controller:
spree_russian_post/app/controllers/admi /orders_controller_decorator.rb
Here is the Code:
require 'spree_core'
Spree::Admin::OrdersController.class_eval do
def sample_method
#order = Order.find_by_param(params[:id]) #Here I get the error
....
end
end
What should I do to get access to the Order class?
Your problem is that Spree thinks you are looking for the constant Spree::Admin::OrdersController::Order
Change your query to #order = Spree::Order.find(params[:id])
Spree will then know that you are looking for the spree object that is associated with the spree_orders table

Resources