Applying foreign key during initialize gives me a view error

Hi all,

I’m trying to set the foreign key of a new Company entity to the
organization id I have in the session.

Here’s the code in Company…

def initialize(org_id)

  if !org_id.nil?
     # Link new company to the organization logged in.
     @organization_id = org_id
  end

end

===============================

…here is the calling code, inside company_controller#edit :

===============================

 @company = params[:id] ? Company.find(params[:id]) : 

Company.new(session[‘org_id’])

===============================

…and finally here is the edit.rhtml view:

===============================

<%= form_tag :controller => “company”, :action => “edit”, :id =>
@company %>
<%= render(:partial => ‘company_form’) %>
<%= end_form_tag %>

===============================

…but I am getting this error when the view is called:

===============================

You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.[]

Extracted source (around line #2):

1:
2: <%= form_tag :controller => “company”, :action => “edit”, :id =>
@company %>
3: <%= render(:partial => ‘company_form’) %>
4: <%= end_form_tag %>

===============================

Can someone see what it is complaining about?

Thanks,
Michael

Michael Wilkes wrote:

def initialize(org_id)

  if !org_id.nil?
     # Link new company to the organization logged in.
     @organization_id = org_id
  end

end

You need to call super in initialize to allow ActiveRecord
to do its stuff first.

Also, did you mean to set the organization_id attribute
rather than an organization_id instance variable?

def initialize(org_id)
super

Link new company to the organization logged in.

self.organization_id = org_id if org_id
end


We develop, watch us RoR, in numbers too big to ignore.