Why does this method not prevent NoMethodError? - ruby-on-rails-3

I'm using the will_paginate gem, and trying to implement DataTables, per this RailsCast, and discovered that it is a good idea to supply the attribute total_entries, because will_paginate apparently does not do this very well.
So I added this method to my class like so:
class Genotype < ActiveRecord::Base
attr_accessible :allele1, :allele2, :run_date
belongs_to :gmarkers
belongs_to :gsamples
def total_entries
#t = Genotype.count;
return #t
end
end
However, I still get this error when the view tries to load (this is a screenshot of the webserver responses):
(7.6ms) SELECT COUNT(*) FROM "genotypes"
Completed 500 Internal Server Error in 96ms
NoMethodError (undefined method `total_entries' for nil:NilClass):
app/datatables/genotypes_datatable.rb:13:in `as_json'
app/controllers/genotypes_controller.rb:7:in `block (2 levels) in index'
app/controllers/genotypes_controller.rb:5:in `index'
Obviously I must be doing something wrong in defining my method; but what? I am too inexperienced in Rails to stumble my way out of this...
Thanks in advance,
Rick

Related

undefined method `[]' for nil:NilClass

I'm following the Michael Hartl tutorial and I found a problem and don't know how solved it... my problem is around here whitout ajax.
when I try to do follow to other user I got this:
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/follows_controller.rb:4:in `create'
here is my "follows" controller eq to relationships
before_filter :authenticate_user!
def create
#user = User.find(params[:follows][:followed_id])
current_user.follow!(#user)
redirect_to #user
end
def destroy
#user = Follow.find(params[:id]).followed
current_user.unfollow!(#user)
redirect_to #user
end
the rest (models,rspec) I have the same
if you need more code tell me, thanks
Chances are that params[:follows] is nil. Check what parameters you're submitting to the create action.

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

Rails 3 + Paperclip: N+1 Query

So, I am using the Bullet gem to try and catch N+1 queries in my Rails 3 app. However, I hit one query that I can't seem to get around.
Here's the bullet message:
N+1 Query detected
User => [:profile]
Add to your finder: :include => [:profile]
N+1 Query method call stack
.../app/models/user.rb:38:in `full_name'
.../config/initializers/paperclip.rb:14:in `block in <top (required)>'
.../app/views/photos/_photo_tiles.html.haml:4:in `_app_views_photos__photo_tiles_html_haml__787318603078146010_2192645460_1634077202131545355'
.../app/views/photos/index.html.haml:30:in `_app_views_photos_index_html_haml___2562222078013468078_2155167020__3275303796392914006'
It doesn't really make sense why it would do this, though, because every user always has profile data that needs to be pulled with them, so my User model has this in it:
# SCOPES
default_scope includes(:profile)
# DELEGATES
delegate :first_name, :last_name, :full_name,
:to => :profile
So, I'm always pulling the profile along with the user. The problem seems to stem from the inclusion of the user's full name in the file name for their uploads, found in my paperclip initializer:
Paperclip.interpolates :username do |attachment, style|
attachment.instance.user.full_name.dehumanize
end
So, that call to user.full_name is being passed through to user.profile -- but profile is included!
So, anyone have any ideas how to eliminate this N+1 query?
Thanks!
Are you sure this is a true instance of N+1 query rather than a mistake by Bullet? Maybe it gets confused by the whole default_scope + delegate thing.
Have you tried running the method in question in script/console development while in another shell doing tail -f log/development.log?
This way you can see which queries are getting executed and make sure that Bullet isn't just confused.

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.

FactoryGirl + RSpec + Rails 3 'undefined method <attribute>='

I'm fairly new to rails and TDD (as will no doubt be obvious from my post) and am having a hard time wrapping my brain around Rspec and FactoryGirl.
I'm using Rails 3, rspec and factory girl:
gem 'rails', '3.0.3'
# ...
gem 'rspec-rails', '~>2.4.0'
gem 'factory_girl_rails'
I have a user model that I've been successfully running tests on during development, but then needed to add an attribute to, called "source". It's for determining where the user record originally came from (local vs LDAP).
In my factories.rb file, I have several factories defined, that look something like the following:
# An alumnus account tied to LDAP
Factory.define :alumnus, :class => User do |f|
f.first_name "Mickey"
f.last_name "Mouse"
f.username "mickeymouse"
f.password "strongpassword"
f.source "directory"
end
I have a macro defined (that's been working up until now) that looks like this:
def login(user)
before(:each) do
sign_out :user
sign_in Factory.create(user)
end
end
I'm calling it in multiple specs like so (example from users_controller_spec.rb):
describe "for non-admins or managers" do
login(:alumnus)
it "should deny access" do
get :index
response.should redirect_to(destroy_user_session_path)
end
end
If I don't specify the "source" attribute, everything works OK, but as soon as I do, I get an error like so when running the test
12) UsersController for non-admins or managers should deny access
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `source=' for #<User:0x00000100e256c0>
I can access the attribute no problem from the rails console and the app itself, and it's listed in my attr_accessible in the user model. It's almost as though Rspec is seeing an old version of my model and not recognizing that I've added an attribute to it. But if I put the following line into my user model, the error disappears
attr_accessor :source
... which indicates to me that it is actually looking at the correct model.
Help!
How about running this?
rake db:test:load
[If you added a new attribute you'd need to migrate it to the test database.]
if you don't use schema.rb (e.g. you have set config.active_record.schema_format = :sql)
you should run
rake db:test:prepare