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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With