ItsJoeTurner
ItsJoeTurner

Reputation: 603

No Method When Importing to Rails via CSV

I'm importing into my Rails App via CSV. The import worked until I tried to create a new contact using one of the columns on my CSV. Here's the code that imports the data:

    row = Hash[[header, spreadsheet.row(i)].transpose]

    hotel = find_by_id(row["id"]) || new
    hotel.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k }

    hotel_name = row["hotel_title"]
    hotel_id = row["id"]

    if row.to_hash["contact_name"]
      hotel.contact = Contact.create(:hotel_id => row["id"], :name => row["contact_name"])
    end

    hotel.map = Map.create(:hotel_id => row["id"], :status => 0, :title => "Map Publication for #{hotel_name}")
    hotel.app = App.create(:hotel_id => row["id"], :status => 0, :title => "Bespoke App for #{hotel_name}")

    hotel.save!

When I run the import, I recieve the following error:

undefined method `contact=' for #

The Contacts belong to the Hotel, and the Hotel has_many Contacts. I have created Contacts using the App, but I'm struggling to get it working using this import method. I'm not sure what I'm doing wrong here, as the Map and App models are both being created (w/ the ID of the Hotel) fine after import. The import now fails when I include the code relating to the contact_name.

class Contact < ActiveRecord::Base
    belongs_to :hotel
end

class Hotel < ActiveRecord::Base
    has_many :contacts  
end

Upvotes: 0

Views: 41

Answers (2)

RAJ
RAJ

Reputation: 9747

Just remove hotel.contact =. You don't need it, as you are explicitly providing :hotel_id while creating the contact record.

So, you need to replace

  if row.to_hash["contact_name"]
      hotel.contact = Contact.create(:hotel_id => row["id"], :name => row["contact_name"])
  end

with

Contact.create(:hotel_id => row["id"], :name => row["contact_name"]) if row.to_hash["contact_name"]

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

You should use << operator, as it's plural association:

hotel.contacts << Contact.create(name: row['contact_name'])

Note that I removed :hotel_id key from parameters, as it would be redundant (it's already set via association).

You can do it also from the other end of association:

Contact.create(name: row['contact_name'], hotel: hotel)

Upvotes: 1

Related Questions