Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create data import into several models in Rails 4?

I'm pretty new with Ruby and Rails framework (but I have good experience with PHP). So my question may look silly.

I have music database and several models like Artist, Album and Song. Song belongs to Artist and Album. It's obvious.

My CSV looks like this:

Artist,Album,Song,Price,Url
"Roxette","Look Sharp!","Listen to Your Heart",1.99,"http://en.wikipedia.org/wiki/Roxette"

Song, Price, Url are stored inside Song model.

Data structure:

Artist
- id
- name

Album
- id
- name

Song
- artist_id
- album_id
- name
- price
- url

Models:

Artist
has_many :songs

Album
has_many :songs

Song
belongs_to :artist
belongs_to :album

I already found Roo and watched Railscasts about Roo. I can import data into one model. But I don't understand how to import data into 3 models at the same time and avoid duplicates.

Also, I would like to know, how to update price and url of songs, when the same songs will be uploaded again.

Please, explain or show how to deal with multi model data import.

I apologize for bad grammar, English is not my native language.

like image 917
zoonman Avatar asked Dec 07 '25 20:12

zoonman


1 Answers

class Artist
  has_many :albums
  has_many :songs

class Album
  has_many :songs
  belongs_to :artist

class Song
  belongs_to :album
  belongs_to :song

when you iterate over the PDF...

artist = Artist.find_or_create_by(name: artist_name)
album = Album.find_or_create_by(name: album_name, artist_id: artist.id)
album.songs << song = Song.create(name: song_name, price: song_price, url: song_url)
album.save
artist.songs << song
artist.save
like image 97
SteveTurczyn Avatar answered Dec 11 '25 10:12

SteveTurczyn