12

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.

2
  • Is this relevant? stackoverflow.com/questions/11945070/… Commented Apr 14, 2014 at 1:02
  • No, I don't need default initial values for the class. The AR answer below was the one that I was looking for. Commented Apr 22, 2014 at 19:19

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That makes sense. I knew I was missing something simple. That said, it would be good if the error message was more descriptive.
Half of this answer is false. You indeed CAN do a def initialize on an AR-inheriting class; however you will need to call super(args) in the initialize block in order for the child class to be initialized properly. Steve is right regarding the columns, if they exist already no need to bother with an initialize block.
@JordanBecker good point, thanks for the edit. I've approved and added clarification about using attr_accessor as an alternative.
You're very welcome, glad you brought up the attr_accessor as well!
@ilasno that's right, although if you explicity specify arguments, they're used instead. Doing super() will pass with no arguments.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.