Rails undefined method 'to_i' - ruby-on-rails-3

When the user creates a new worequest, I want to set the worequest.statuscode_id to the first entry in the statuscodes table.
The following (from worequest.rb) was working in Rails 3.1 but now I've upgraded to 3.2, it's not working.
after_initialize :defaults
def defaults
self.statuscode_id ||= Statuscode.first
end
I get
undefined method `to_i' for #<Statuscode:0x007fe934b67bd0>
Any idea why this doesn't work now? Do you know something that will work?
Thanks!

Related

Rails 5 Minitest ActionView::Template::Error: nil is not a valid asset source

I upgraded my Rails Application from 4.2 -> 5.0.0.1.
Other TESTS works fine (e.g. Model, Helper, Feature), but havinf trouble with my Controller Test.
I have read about Keyword arguments in controller & integration tests in Rails 5. So I changed the code structure as given below...
ActionView::Template::Error: nil is not a valid asset source
setup do
#logo = plogos(:main_logo)
end
test "should get edit" do
puts #logo.id // just to check...working fine
get :edit, params: {id: #logo.id}
assert_response :success
end
But I got new error with ActionView.
Is there anyone encountered and fixed the same issue, please help!
Thank you!
You may want to add some logtrace, probably it hints you where it went wrong.
May it be that the main_logo-fixture doesn't have an image? Since Rails 5 image_tag raises this error when given an nil-value, see also: Rails, "nil is not a valid asset source" for a particular image_tag (Carrierwave)
Besides that, typically the new scaffolded code would look as follows:
require 'test_helper'
class LogosControllerTest < ActionDispatch::IntegrationTest
setup do
#logo = plogos(:main_logo)
end
#...
test "should get edit" do
get edit_logo_url(#logo)
assert_response :success
end
#...
end

Devise Parameter Sanitizer "For" Method Not Found Rails 5

I have just added devise to my shiny new Rails 5 app. All's good and dandy until I try to add a username to the Devise user model. Everything worked until I ran it and went to localhost:3000/users/sign_up, where I was greeted by this error:
undefined method `for' for #<Devise::ParameterSanitizer:0x007fa0dc31c1b0> Did you mean? fork
I have searched the wonderful place of Google for any results, only being given outdated, Rails 4 errors and solutions, the same with searching Stack Overflow itself. I cannot get my mind to find a working solution. I would appreciate help very much. Here is how I prepared for this:
Create the migration: rails generate migration add_username_to_users username:string:uniq
Migrate the database rake db:migrate
Add strong parameters to the application controller devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(..) }
Add username parameters to the Devise views
Restart the server
Is there anything I missed or did wrong?
The .for method is deprecated, from devise 4.1+ .permit method is available
Try .permit. It should work.
devise_parameter_sanitizer.permit(:my_action) { |u| u.permit(..) }
Hope this will help you :)
The problem was well mentioned by #Shadow but this syntax worked for me:
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :email])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :phone, :email, bank_attributes:
[:bank_name, :bank_account]])
end

Activeadmin - undefined method `batch_action'?

I'm trying to use activeadmin's batch_action so I can run actions on more than one record. However when trying to run my rails server I get the following error.
undefined method `batch_action' for #<ActiveAdmin::ResourceDSL:0xb11f980> (NoMethodError)
Here is the activeadmin resource code:
ActiveAdmin.register Product do
batch_action :destroy, false
filter :name
index do
selectable_column
column :name
default_actions
end
controller do
def current_company
#current_company
end
end
end
I'm not sure where I'm getting it wrong - I need to show a corresponding checkboxes against the records and then define a batch action. Where am I getting it wrong here?
Got the answer :) was a wrong entry in my gemfile.
https://github.com/gregbell/active_admin/issues/1302

stringify_keys error after supplementing session variables in functional tests

I'm in the process of upgrading to Rails 3.1.0 from 3.0.10, and I'm using Devise for authentication.
I have a number of functional tests that require me to set a single session variable. Stuff along the lines of:
test "new clears current_lesson_id from session" do
get :new, nil, {'current_lesson_id' => '234234'}
assert_response :success
assert_nil session[:current_lesson_id]
end
This was failing as my session info was clobbering the devise authentication session data, so my previous solution was to merge with the default session:
test "new clears current_lesson_id from session" do
get :new, nil, authenticated_sesion_with({'current_lesson_id' => '234234'})
assert_response :success
assert_nil session[:current_lesson_id]
end
def authenticated_session_with(hash)
session.merge(hash)
end
All of this worked fine with rails 3.0.10 (with warden 1.0.4 and devise 1.4.2), but no longer with rails 3.1.0 (and warden 1.0.5, devise 1.4.4). Now I'm getting the following error:
NoMethodError: private method `stringify_keys' called for <ActionController::TestSession:0x000001060db590>
I gather this is because the 'session' object is an instance of ActionController::TestSession, and in rails 3.1.0 there are a bunch of instance variables that can't and shouldn't be 'stringified'.
How should I properly access the devise user information (preferably dynamically) so I can add 'current_lesson_id', etc.?
Thanks much,
try this to fix your error in Rails 3.1
sign_in user
hashy = session['warden.user.user.key'][2]
get :action, nil, {"warden.user.user.key"=>["User", [user.id],hashy]}, nil
Worked for me. Seems to not like the new way Rails handles TestSessions.
I think you better do:
def valid_session
my_session_values = {:some_key => :some_value}
session.to_hash.merge my_session_values
end

rails3-amf - to_amf method not found on ActiveRecord objects

I am using the rails3-amf gem by warhammerkid in my Rails 3 / Flex 4 project.
AFAIK, I have correctly followed the "Getting Started" instructions from the GitHub page.
I have added the gem lines to my Gemfile.
I have installed the gems using bundle install.
From my Flex application, I will be making the RemoteObject call to the index action in the ManageMySchool::GradesController file. This is the code in the app/controllers/manage_my_school/grades_controller.rb file:
class ManageMySchool::GradesController < ApplicationController
respond_to :html, :amf
def index
#grade = Grade.first
respond_with(#grade) do |format|
format.amf { render :amf => #grade.to_amf }
end
end
end
The name of the model which is to be serialized is called Grade in both the Rails project (app/models/Grade.rb) and the Flex project (Grade.as with a RemoteAlias set as Grade). In the config/application.rb file, I have done the class mapping this way:
config.rails3amf.class_mapping do |m|
m.map :as => 'Grade', :ruby => 'Grade'
end
And I have done a parameter mapping this way:
config.rails3amf.map_params :controller => 'ManageMySchool::GradesController', :action => 'index', :params => [:authenticity_token]
Problem
Now, when I run the server and make the RemoteObject call from Flex, I get a to_amf undefined method error for the Grade model.
If I change Grade.first to Grade.all, #grade would have an array of Grades. But the undefined method error message still mentions the Grade model. This means that the to_amf method is working for the Array class but not for the ActiveRecord model.
Why is this? What am I doing wrong?
Is there something I have to do to "enable" the rails3-amf gem for ActiveRecord models?
I would appreciate any insights. Thanks!
Update
#warhammerkid: Here is the output of Grade.ancestors as seen in rails console.
ree-1.8.7-2011.03 :006 > puts Grade.ancestors
Grade
ActiveRecord::Base
Paperclip::CallbackCompatability::Rails3::Running
Paperclip::CallbackCompatability::Rails3
Paperclip::Glue CanCan::ModelAdditions
Authlogic::ActsAsAuthentic::ValidationsScope
Authlogic::ActsAsAuthentic::SingleAccessToken
Authlogic::ActsAsAuthentic::SessionMaintenance
Authlogic::ActsAsAuthentic::RestfulAuthentication::InstanceMethods
Authlogic::ActsAsAuthentic::RestfulAuthentication
Authlogic::ActsAsAuthentic::PersistenceToken
Authlogic::ActsAsAuthentic::PerishableToken
Authlogic::ActsAsAuthentic::Password
Authlogic::ActsAsAuthentic::MagicColumns
Authlogic::ActsAsAuthentic::Login
Authlogic::ActsAsAuthentic::LoggedInStatus
Authlogic::ActsAsAuthentic::Email
Authlogic::ActsAsAuthentic::Base
ActiveRecord::Aggregations
ActiveRecord::Transactions
ActiveRecord::Reflection
ActiveRecord::Serialization
ActiveModel::Serializers::Xml
ActiveModel::Serializers::JSON
ActiveModel::Serialization
ActiveRecord::AutosaveAssociation
ActiveRecord::NestedAttributes
ActiveRecord::Associations
ActiveRecord::AssociationPreload
ActiveRecord::NamedScope
ActiveModel::Validations::Callbacks
ActiveRecord::Callbacks
ActiveModel::Observing
ActiveRecord::Timestamp
ActiveModel::MassAssignmentSecurity
ActiveRecord::AttributeMethods::Dirty
ActiveModel::Dirty
ActiveRecord::AttributeMethods::TimeZoneConversion
ActiveRecord::AttributeMethods::PrimaryKey
ActiveRecord::AttributeMethods::Read
ActiveRecord::AttributeMethods::Write
ActiveRecord::AttributeMethods::BeforeTypeCast
#<Module:0x1028356f0> ActiveRecord::AttributeMethods::Query
ActiveRecord::AttributeMethods
ActiveModel::AttributeMethods
ActiveRecord::Locking::Optimistic
ActiveRecord::Locking::Pessimistic
ActiveRecord::Validations
ActiveModel::Validations::HelperMethods
ActiveModel::Validations
ActiveSupport::Callbacks
ActiveModel::Conversion
ActiveRecord::Persistence Object
PP::ObjectMixin Base64::Deprecated
Base64
ActiveSupport::Dependencies::Loadable
Kernel
Note that only ActiveModel::Serialization is there. No mention of Rails3AMF.
Does this mean I have to do something special to load the Rails3AMF module for the ActiveRecord models?
I am using Rails 3.0.5 with the latest version of ree. The gems are all contained in a gemset managed using rvm.
Update 2
If I remove the to_amf in the render :amf line, then I get the following error:
Grade Load (0.3ms) SELECT `grades`.* FROM `grades` LIMIT 1
Completed 200 OK in 195ms (Views: 0.1ms | ActiveRecord: 0.8ms)
Sending back AMF
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.last):
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.8ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (13.6ms)
Started POST "/amf" for 127.0.0.1 at Fri Apr 15 17:03:34 +0530 2011
Sending back AMF
Update 3
If I manually add the line include Rails3AMF::Serialization at the top of the Grade.rb model file, then it all works. So, does this mean that I have to put this line in all my models?
I see that this is already being done in line numbers 40 - 42 in the lib/rails3-amf/serialization.rb file of the gem:
# Hook into any object that includes ActiveModel::Serialization
module ActiveModel::Serialization
include Rails3AMF::Serialization
end
Why isn't this working? Should I force-load the gem when my application initializes or something?
Thanks!
Update 4 - Solved by this workaround
Okay, I just ended up adding this code block in an initializer:
class ActiveRecord::Base
include Rails3AMF::Serialization
end
And it is working.
#warhammerkid - Thanks for the help.
Rails3AMF::Serialization, the module that adds the to_amf method, is included in ActiveModel::Serialization when Rails3-AMF loads. If it's somehow not being included even though the code is running and ActiveModel::Serialization is one of your model's ancestors, then the simplest solution is just to add "include Rails3AMF::Serialization" at the top of your model implementation. I've never tried gem sets before, but it might be an issue with them, as everything works correctly using Bundler.
As an aside, feel free to post a bug to https://github.com/warhammerkid/rails3-amf/issues.