Martijn Kerckhaert
Martijn Kerckhaert

Reputation: 494

Undefined method for Array when exporting to excel

I need to export some data in our database in an excel.

A person can be linked to multiple organisations and I need to get the communication details of the organisations they are linked to.

Currently I'm checking in my table OrganisationContacts which organisations are linked to which contact.

That returns me an array of objects of the organisations that are linked to that person.

Then I loop through those organisations and take the communication_id so I can find the correct communication details linked to that organisation.

The last step is simply looping over the Array of Communication objects and taking the email for example.

The last step is where it goes wrong. I keep getting (undefined method `tel' for #).

When I inspect the element I get this in the excel file: orgrow.inspect =>

Communication id: 12048, tel: "+32 2 552 60 00", fax: "+32 2 552 60 01", gsm: "", email: "[email protected]", website: "", other: "Kabinet van de minister-president van de Vlaamse re...", created_at: nil, updated_at: "2014-09-15 14:00:11", contact_id: nil, organisation_id: 1564, organisationcontact_id: nil

So I should be able to get the .tel, right?

The log makes me think I am doing the method on the array and not on the object itself but this should not be the case.

This is my code currently:

<% @org_row = [] %>

  <ss:Cell><ss:Data ss:Type="String">

    <% @org_ids.each do |orgid| %>
      <% if orgid.to_i > 0 %> <% @org_row << Communication.all(:conditions => {:organisation_id => orgid.to_i }) %>
      <% end %>
    <% end %>

  <% @org_row.each do |orgrow| %>
    <%= orgrow.tel %>
  <% end %>
</ss:Data></ss:Cell>

Upvotes: 0

Views: 52

Answers (2)

ex0ns
ex0ns

Reputation: 1116

You have a n+1 queries issue, with this code you're going execute as many queries as the number of organisation, you must avoid that, you should instead query the association in the query in the first place (the query for @org_ids) here is what I would do (you didn't give us this query so I will have to do some assumptions..):

@org = OrganisationContacts.all.includes(:communication)

You might now be able to to

<% @org.each do |org| %>
  <% @org.communication.each do |comm| %>
    <%= comm.tel %>
  <% end %>
<% end %>

If you want a more precise anwser, please give us the details of OrganisationContacts and your query for @org_ids

Upvotes: 1

Ankita Tandel
Ankita Tandel

Reputation: 202

Here you need a single Active Record. Using .all on model, you will get collection in array. So change your query like this

Communication.first(:conditions => ["organisation_id => ?", orgid.to_i])

Upvotes: 1

Related Questions