How to create import of data to multiple models in Rails 4?

I am new to Ruby and Rails (but I have good experience with PHP). So my question might look silly.

I have a music database and several models like Artist

, Album

and Song

. The song belongs to Artist

and Album

. It is 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 the model Song

.

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 looked at 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 the price and URL of songs when the same songs are downloaded again.

Please explain or show how to work with importing multiple models.

Sorry for poor grammar, English is not my first language.

+3


source to share


1 answer


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

      

+5


source







All Articles