Reputation: 881
The following is my current code. I removed parts not needed to understand the problem.
Setting Model
class Setting < ActiveRecord::Base
attr_accessor :program_id, :session_types
def initialize
@session_types = Array.new
@program_id = ''
end
end
Setting Controller
def new
@setting = Setting.new
puts @setting.session_types.instance_of? Array
end
Setting View
<%= form_for(@setting) do |f| %> #ERROR LINE
...
<% end %>
I get this error:
ActionView::Template::Error (undefined method `[]' for nil:NilClass):
3: </h1>
4: <p>We need to get your booking page setup. Please select the Program you wish to put up for booking.</p>
5:
6: <%= form_for(@setting) do |f| %>
7: <% @programs.each do |program| %>
8: <%= f.radio_button(:program_id, program.program_id)%>
9: <%= label_tag(:program_name, program.name) %>
app/views/settings/new.html.erb:6:in `_app_views_settings_new_html_erb__94314060479739781_70294544827460'
@setting.session_types = Empty Array
when debugging.
So I tried replacing Setting Model
with a simple Testing Model
without the array attribute as follows:
class Testing < ActiveRecord::Base
attr_accessor :program_id
end
to see if it is the Array
attribute session_types
of Setting
that is causing the error. It seems so becuase with Testing
, I get an error in the line AFTER the form_for
line, which should be correct. (the line is not needed to undestand the problem)
I think I am not understanding the initialization of an Array
attribute of a model properly. Any help to understand why the error is thrown will be appreciated! Thanks in advance! =D
Upvotes: 3
Views: 426
Reputation: 2390
Try this
def initialize
super
@session_types = Array.new
@program_id = ''
end
You were very scarce with pasting your errors, but that's the first thing that comes to mind. Please post the entire error if this doesn't help.
The reason for that is your Setting
class inherits from ActiveRecord::Base
, calling super
first calls parent's initialize
method, this way you add functionality to the method (extend it). Without super
you override it, meaning you replace everything it does by default (like for example connecting to the database, validating) by your code.
Upvotes: 4
Reputation: 3113
Do not override initialize
method on ActiveRecord::Base
. Use after_initialize
callback instead. Reference possibly with your problem http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html
Upvotes: 2