Forum: Ruby on Rails Importing flat CSV into two tables and maintaining a relatio

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fdb969158f6b65ebfd0d1a3442975d52?d=identicon&s=25 Jay (Guest)
on 2007-06-25 22:27
(Received via mailing list)
Hello,


I'm new to Ruby on Rails and I've been really enjoying the framework.
I have recently hit a wall that I can't seem to get around. I've
searched to web and haven't found an answer(and my agile development
with rails book hasn't arrived).....


My problem:  I have a CSV file that has information about  recreation
programs, and the buildings that each program is housed in.  It is in
a one line format.


So,


Building name | Location | Program name | Description of program |
Time |


Buildings have many programs, but programs only have one building.

I need to import this CSV into a mysql database.  I can do this using
migrations and FasterCSV.  There are duplicate entries for buildings,
and I only want each building entered into the database once, which I
could use validates uniqueness to ensure.

The wall I've encountered is how do I maintain the relationship
between programs and buildings throughout this import process?

Ie I want to be able to list the programs in each building...

Many Thanks and apologies if there is a very obvious solution that I
am missing,

Jay
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2007-06-25 23:54
(Received via mailing list)
On Jun 25, 2007, at 4:27 PM, Jay wrote:
>
> could use validates uniqueness to ensure.
>
> The wall I've encountered is how do I maintain the relationship
> between programs and buildings throughout this import process?
>
> Ie I want to be able to list the programs in each building...
>
> Many Thanks and apologies if there is a very obvious solution that I
> am missing,
>
> Jay

Use:

   current_building = Building.find_or_create_by_name(bldg_name)

If you need to do something differently when the Building was created
(like setup more attributes), you can:

   # new_record? is false on create, but nil on find
   unless current_building.new_record?.nil?
     ...
   end

Then I assume you have something like:

   current_building.programs.create(...)

or:

   new_program.building = current_building

when you create the new program from the CSV data.

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
This topic is locked and can not be replied to.