Rails 3 - Paperclip: uninitialized constant ActionDispatch::Request::UploadedFile - ruby-on-rails

I have a confusing error:
I run Rails 3.0.0 on Ruby 1.9.2 with Paperclip 2.3.5.
When I upload a file I get a 500 error.
NameError (uninitialized constant ActionDispatch::Request::UploadedFile):
config/initializers/fix_params.rb:13:in `normalize_parameters'
config/initializers/fix_params.rb:19:in `block in normalize_parameters'
config/initializers/fix_params.rb:19:in `each'
config/initializers/fix_params.rb:19:in `normalize_parameters'
config/initializers/fix_params.rb:19:in `block in normalize_parameters'
config/initializers/fix_params.rb:19:in `each'
config/initializers/fix_params.rb:19:in `normalize_parameters'
Rendered /Users/vjmayr/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (10.2ms)
I have seen similar things happen with Rails 3.0.2 and .3 but I have no idea why it happens here. Con anyone help me with finding the problem?
Thanks! Valentin
ADDED config/initializers/fix_params.rb:
module ActionController
class Request
private
# Convert nested Hashs to HashWithIndifferentAccess and replace
# file upload hashs with UploadedFile objects
def normalize_parameters(value)
case value
when Hash
if value.has_key?(:tempfile)
upload = value[:tempfile]
upload.extend(UploadedFile)
upload.original_path = value[:filename]
upload.content_type = value[:type]
upload
else
h = {}
value.each { |k, v| h[k] = normalize_parameters(v) }
h.with_indifferent_access
end
when Array
value.map { |e| normalize_parameters(e) }
else
value.force_encoding(Encoding::UTF_8) if value.respond_to?(:force_encoding)
value
end
end
end
end

tadman (Thanks!) pointed me towards the right solution:
All I had to do was change the value from tempfile to to_tempfile. This prabably won't happen to too many people, but I thought I'd mention as there has been a similar discussion around that due to a recent change in stable rails 3.0.3 by tenderlove, which is philisophically absolutely correct - but threw off some people...
So here is the changed fragment of fix_params.rb
...
if value.has_key?(:to_tempfile)
upload = value[:to_tempfile]
...
Cheers,
Val

Related

STORYBLOK, RUBY: undefined method `[]' for nil:NilClass (NoMethodError)

I don't know that much about RUBY, just thought that you guys might help me with this. I'm using Storyblok as my headless CMS and JEKYLL when I'm building serve it this is the error that I got;
33: from C:/project/test/_plugins/storyblok_generator.rb:8:in `generate'
32: from C:/project/test/_plugins/storyblok_cms/generator.rb:12:in `generate!'
C:/project/test/vendor/cache/ruby/2.7.0/gems/storyblok-3.0.1/lib/storyblok/client.rb:354:in `block (2 levels) in find_and_fill_links': undefined method `[]' for nil:NilClass (NoMethodError)
the code below is from _plugins/storyblok_cms/generator.rb
def generate!
timestamp = Time.now.to_i
links = client.links(cv: timestamp)['data']['links']
stories = client.stories(per_page: 100, page: 1, cv: timestamp)['data']['stories'] #line 12
stories.each do |story|
# create all pages except global (header,footer,etc.)
content_type = story['content']['component']
if content_type != 'shared'
site.pages << create_page(site, story, links)
end
rescue UnknownContentTypeError => e
# for production, raise unknown content type error;
# for preview and other environments, issue an warning only since the content_type might be available
# but the code handling that content type might be in a different branch.
Jekyll.env == 'production' ? raise : Jekyll.logger.warn(e.message)
end
site.data['stories'] = stories
site.data['articles'] = stories.select { |story| story['full_slug'].start_with?('articles') }
site.data['shared'] = stories.select { |story| story['full_slug'].start_with?('shared') }
end
the code below is from _plugins/storyblok_generator.rb
require "storyblok"
module Jekyll
class StoryblokGenerator < Jekyll::Generator
safe true
def generate(site)
StoryblokCms::Generator.new(site).generate! #line 8
end
end
end
Additional Info:
ruby version: ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x64-mingw32]
jekyll version: jekyll 4.2.1
OS: Windows 10
I've actually found the solution to this, So this error occurs because I have created a page template in Block Library in Storyblok and then firing bundle exec jekyll serve command in terminal without creating the page template source/file in my project directory.
So I have an about_us block (content-type) in Block Library created and then when I fire bundle exec jekyll serve without creating an about_us.html first in _layouts folder, It would trigger the error.
Solution;
Make sure to create the source/file first in the _layouts folder if you have created a block (content-type) in block library.

How do I screen for integers that are too big in my Rails model?

Iā€™m using Rails 4.2.7 with PostGres 9.5. I have this column in my Rails migration ...
my_num | integer |
In my model, I would like to screen for numbers that are too big and set them to nil. For instance, the number ā€œ659722222222222ā€ is getting set on my model and is causing the below error
Error during processing: (RangeError) 659722222222222 is out of range for ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer with limit 4
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:45:in `ensure_in_range'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:23:in `type_cast_for_database'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/quoting.rb:13:in `quote'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:641:in `block (2 levels) in values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each_with_index'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `map'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `block in values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `map'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:530:in `import_without_validations_or_callbacks'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:490:in `import_with_validations'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:417:in `import_helper'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:331:in `import'
/Users/davea/Documents/workspace//app/services/abstract_import_service.rb:161:in `block in save_my_object__time_results'
Rather than save the model, I would like to set the field to nil only if it is set to an integer value that is too big for PostGres SQL. How do I do this?
Note, I do NOT want to change teh column type of the PostGres column. You didn't think this was going to be that easy, did you?
2147483647 is the max value of the type integer in Postgres.
before_save :is_too_big
def is_too_big
if my_num > 2147483647
# do something
end
end
If you don't want put a magic numbers to the code, I suggest you catch an exeption when the out of range happens:
# somewhere in the code
u = User.new(my_num: 2147483648)
begin
u.save
rescue RangeError => e
u.my_num = nil
u.save
end
Add a before validation event
before_validation :ensure_my_num_ok
and just set the value if it's bad
def ensure_my_num_ok
self.my_num = nil if my_num > 100000000
end

How do I implement a decorator in my app?

I am trying to implement this in my app.
The article says that I must create a decorator - but it doesn't go into much detail about exactly how to do that. This is the code:
module CartDecorator
extend ActiveSupport::Concern
module InstanceMethods
def is_downloadable?
items = self.items.collect { |li| li[:variant].item }
items.all? { |i| i.is_downloadable }
end
def has_downloadable?
items = self.items.collect { |li| li[:variant].item }
items.any? { |i| i.is_downloadable }
end
end
end
Piggybak::Cart.send(:include, CartDecorator)
I am not sure if I should add that code to some model.rb (for what it's worth, I don't have a piggybak_cart.rb in my app/models/ folder).
I tried running rails g decorator Cart and that didn't work.
What I have done is put the above code in app/helpers/cart_helper.rb.
Then when I tried to run a rails g command (for something else), I am now getting this error:
/.rvm/gems/ruby-2.0.0-p0#myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in `block in constantize': uninitialized constant CartHelper (NameError)
from /.rvm/gems/ruby-2.0.0-p0#myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `each'
from /.rvm/gems/ruby-2.0.0-p0#myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `constantize'
from /.rvm/gems/ruby-2.0.0-p0#myapp/gems/activesupport-3.2.13/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
from /.rvm/gems/ruby-2.0.0-p0#myapp/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:136:in `block in modules_for_helpers'
from /.rvm/gems/ruby-2.0.0-p0#myapp/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:131:in `map!'
What's the best way to approach this?
You should add the above code into app/decorators/cart_decorator.rb
the decorators folder will be new and be autoloaded when you start your rails app. when this is run Piggybak::Cart.send(:include, CartDecorator) it will decorate your Piggybag::Cart with the methods you declared above.

How to set up rack-offline in rails 3.2 app

How to make rake-offline work in rails 3.2.11 ?
I added initializer
offline = Rack::Offline.configure do
#cache "images/masthead.png"
public_path = Rails.public_path
Dir[public_path.join("javascripts/*.js")].each do |file|
cache file.relative_path_from(public_path)
end
network "/"
end
I added in routes
match "/application.manifest" => Rails::Offline
Rack::Offline.configure do
cache "assets/application.js"
cache "assets/application.css"
network "/"
end
and added manifest in html tag.
It throws error
/initializers/offline.rb:5:in `block in <top (required)>': undefined method `join' for "/Sites/Ruby/project/public":String (NoMethodError)
In Rails 3.2.11, Rails.public_path returns a String, not a Pathname object. (It looks like Rails master has it returning a Pathname object which is why rack-offline's documentation might say to use it that way).
Try this instead:
public_path = Pathname.new(Rails.public_path)
See https://github.com/wycats/rack-offline/issues/7

New to Ruby trying to learn how to debug

I am migrating data from a database and getting an error I cannot understand. I am new to Ruby and am looking for both what is wrong with my code and also the most effective commands for debugging. I cannot even really read my error.
Here is my error:
/Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activemodel-3.0.6/lib/active_model/attribute_methods.rb:367:in `method_missing': undefined method `answer=' for #<Question:0x00000102d59758> (NoMethodError)
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:46:in `method_missing'
from ./script/migrate.rb:139:in `block (2 levels) in <main>'
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/relation.rb:13:in `each'
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/relation.rb:13:in `each'
from ./script/migrate.rb:137:in `block in <main>'
from ./script/migrate.rb:111:in `each'
from ./script/migrate.rb:111:in `<main>'
Any tips for reading this error and for how to debug.
Note here is my code:
NetworkCommunications.all.each do |nc|
if nc.NETWORK_COMM_TYPE_ID==1 && nc.SENDER_CONSUMER_ID != 0
q = Question.new
q.created_at = nc.LAST_MOD_TIME
category = CommunicationInterestMapping.where(:COMMUNICATION_ID => nc.COMMUNICATIONS_ID).first
if category
cie = ConsumerInterestExpertLookup.find(category.CONSUMER_INTEREST_EXPERT_ID)
if cie
q.category = Category.find_by_name cie.CONSUMER_INTEREST_EXPERT_NAME
else
puts "No category"
end
end
message = NetworkCommunicationsMessage.where(:COMMUNICATIONS_ID => nc.COMMUNICATIONS_ID).first
q.title = message.SUBJECT
q.description = message.MESSAGE
q.permalink = message.QUESTION_SLUG
email = find_email_from_consumer_id(nc.SENDER_CONSUMER_ID)
q.user = User.find_by_email email
children = NetworkCommunications.where(:PARENT_COMMUNICATIONS_ID => nc.COMMUNICATIONS_ID)
puts children
if children
children.each do |ncc|
if ncc.NETWORK_COMM_TYPE_ID == 2
q.answer = Answer.new
q.answer.created_at = ncc.LAST_MOD_TIME
message_a = NetworkCommunicationsMessage.where(:COMMUNICATIONS_ID => ncc.COMMUNICATIONS_ID).first
q.answer.text = message_a.MESSAGE
email_a = find_email_from_consumer_id(ncc.SENDER_CONSUMER_ID)
q.answer.user = User.find_by_email email_a
end
end
end
begin
q.save!
rescue Exception => e
puts "Exception: #{e} title: #{message.SUBJECT}"
end
end
end
To read the stack dump, look at the first line then read downwards:
/Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activemodel-3.0.6/lib/active_model/attribute_methods.rb:367:in `method_missing': undefined method `answer=' for #<Question:0x00000102d59758> (NoMethodError)
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:46:in `method_missing'
from ./script/migrate.rb:139:in `block (2 levels) in <main>'
The first line tells you where the problem was triggered and why: In ActiveModel's attribute_methods method because no setter for answer was found in the object. This was triggered from a call in line 139 of your migrate.rb script. The trick with a stack trace is to read through it, looking for the scripts you've written. Odds are really good the problem is in our code so it's always good to start from the assumption the bug is ours.
if ncc.NETWORK_COMM_TYPE_ID == 2
q.answer = Answer.new
is where the problem is. Your Question class doesn't have a setter for answer. Either you're missing or misspelled an attribute_accessor call or misspelled a def answer= method.
To debug I recommend using Ruby Debugger 1.9. gem install ruby-debug19. It's 1.9.2 studly and easy to use. You can set a breakpoint in your code, then run it from the command-line, which will run until the breakpoint is reached and will stop in the debugger. From there you can list the current lines using l, display the contents of variables using p or do a require 'pp' if you have pretty-printer installed. You can single-step into methods using s or step over them using n, for "next". There's also c to continue, c 100 to continue to a particular line number; 100 in that example. You can use b 100 to set a break-point at line 100, and then c to run, stopping at 100 every time. irb will drop you into IRB with the variables to that point already initialized so you can poke at them. There are lots of other commands, but those are the ones I use most often.
It probably means you have defined the answer attribute for your question class:
class Question < ActiveRecord::Base
attr_accessor :answer
[...]
end
You should also learn how to use rdebug so that you can step through the code and figure this out without help.
I think your model Question doesn't have answer attribute.
In this cast you can study how to debug rails app

Resources