Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Error when using either .create or .new with Rails 3

Posted on 2011-03-08
Medium Priority
Last Modified: 2013-11-13
I have an application that worked in rails 2.3.8, but now trying to convert to rails 3 and things aren't working like I would expect.

I have a model (and table) called 'session_log' (model is SessionLog).  This table contains information about the current user (logged in status, User ID etc.).

In additon, I used the command rake:db:sessions:create which created the table 'sessions'.  I'm not sure I understand the implications of this completely but don't think that is impacting what I'm dealing with.

The issue is that in the application_controller.rb file, I have a method defined as follows:

def get_session

    rescue ActiveRecord::RecordNotFound

    session_log = SessionLog.create
    session[:session_log_id] = session_log.id


This code is mostly copied from the agile web development book (for rails 3).

the code in the controller that calls this method is as follows:

@current_session = get_session

When I run this code, I get an error 'wrong number of arguments (1 for 0)' and I can't figure out why this would be the case.
The get_session method does not expect (nor do I pass) an argument.  the only thing I could think of is that the .create method was
expecting an argument, although I've read code examples that suggest this isn't the case.

I tried using .new (session_log = SessionLog.new) instead, and get a different error 'You have a nil object when you didn't expect it' and 'you might have an instance of ActiveRecord::Base'.

Any help in pointing me in the right direction would be appreciated

Question by:rlbertke
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2

Expert Comment

ID: 35070158
Using .new instead of .create would not attempt to save the record in the database (not what you want, I presume), so session_log.id and session[:session_log_id] are expected to be nil. Maybe you were calling an ActiveRecord::Base method on the get_session result or session[:session_log_id] elsewhere causing the "You have a nil object when you didn't expect it" error?

Anyway, your get_session method looks fine. Will you be able to give us your code in the area where the error occurs? Look for the line number. If you added another rescue elsewhere and only print out the more readable form of the error, it might be useful to remove this temporarily so you could see the line number.

Author Comment

ID: 35075156
I just noticed something interesting.  The code for the model has an initialize method in it.  When i comment that out, I don't get an error (it works) but if I include the method, even with all the code inside commented out, it still doesn't work.  Any reason why this would be the case?

Below is the initialize method in the class SessionLog

  def initialize
#    @logged_in = "False"
#    @created_at = DateTime.now

Accepted Solution

kristinalim earned 2000 total points
ID: 35076451
Is logged_in really meant to be a string or is that a typo?

You are overriding the ActiveRecord::Base initialize(attributes = nil) method of ActiveRecord::Base which allows one parameter with a method that does not allow a parameter. There are various places throughout ActiveRecord::Base that call this with a parameter, and ActiveRecord::Base create(...) is only one of these.

The more common way of achieving your goal would be with ActiveRecord::Base initialize():

def after_initialize
  @logged_in = false
  @created_at = DateTime.now

Open in new window

Slightly unrelated concerns especially if any of these attributes are non-virtual:

Line 3: By default, a :created_at non-virtual attribute will automatically be set to the date and time the record is saved. In most circumstances, there is no need to set it yourself.

Line 2: :logged_in will be set to false in the following scenarios as well. Consider setting the default for :logged_in in the DB instead, or setting only if an unsaved record (new_record?) and if not changed (!logged_in_changed?).

MyModel.new(:logged_in => true)

Open in new window


Expert Comment

ID: 35076516
Correction: The more common way of achieving your goal would be with ActiveRecord::Base after_initialize().

Author Closing Comment

ID: 35082409
This helped immensly.  The 'logged_in' sadly was created as a string.  This was my first RoR project and when I first created these attributes I didn't want to get bogged down with data types.  This project is 99% web site with 1% database/user interaction and I wasn't concerned with getting things right as much as getting them working.

The app worked fine in RoR 2.3.8, but (with the initialize ovverride) but porting to Rails 3, it stopped liking this.  

I changed to use the after_initialize method and it works great and I get the fact that I'm overriding a method that previously expected a parameter.

I also appreciate the additional feedback on using the model to set the default values.  Thank you!

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question