Solved

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

Posted on 2011-03-08
5
522 Views
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
    SessionLog.find(session[:session_log_id])

    rescue ActiveRecord::RecordNotFound

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

end

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


0
Comment
Question by:rlbertke
  • 3
  • 2
5 Comments
 
LVL 4

Expert Comment

by:kristinalim
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.
0
 

Author Comment

by:rlbertke
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
  end
0
 
LVL 4

Accepted Solution

by:
kristinalim earned 500 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
end

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)
MyModel.find(id_of_record_with_true_logged_in)

Open in new window

.
0
 
LVL 4

Expert Comment

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

Author Closing Comment

by:rlbertke
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!
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

I recently rediscovered rails when I needed a holiday project and decided to build a management dashboard for the company where I work.  With it being a project done in my free time, I could focus my time on learning the basics rather than trying to…
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…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

820 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