Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Class.new gives "Class not initialized" error in rails console

I'm creating a lightweight app to create and display information for upcoming events. I have an Event class defined that takes an args hash as a parameter. The initialize method is defined below.

class Event < ActiveRecord::Base

  def initialize(args={})
    @what       = args[:what]
    @theme      = args[:theme]
    ... 
  end
end

So far, so good. Then, in Rails Console, I define an args hash and try to create an instance of Event but get the following error.

[4] pry(main)> args = {what: 'what', theme: 'theme'}
=> {:what=>"what", :theme=>"theme"}
[5] pry(main)> Event.new(args)
=> #<Event not initialized>

This seems really straightforward but I'm having trouble figuring it out. Any help is appreciated.

like image 682
darkmoves Avatar asked Apr 14 '14 00:04

darkmoves


1 Answers

If you want to do a def initialize block for ActiveRecord-inheriting classes, you have to call super(args) inside this block in order for the subclass to be properly initialised.

However, if what and theme already exists as columns in your model, you don't need the initialize method: Event.new(args) will work fine out of the box.

A good practice would be to only use initialize block when you need to define variables that are not present in your ActiveRecord schema (e.g. setting instance variables that do not need persistence), but if you need to do that then it's the more common practice to use attr_accessor.

like image 55
SteveTurczyn Avatar answered Sep 22 '22 07:09

SteveTurczyn