如何在Rails 4中创建数据导入到多个模型?

zoo*_*man 3 ruby ruby-on-rails-4

我是Ruby和Rails框架的新手(但我有很好的PHP经验).所以我的问题可能看起来很傻.

我有音乐数据库和几款车型一样Artist,AlbumSong.宋属于ArtistAlbum.很明显.

我的CSV看起来像这样:

Artist,Album,Song,Price,Url
"Roxette","Look Sharp!","Listen to Your Heart",1.99,"http://en.wikipedia.org/wiki/Roxette"
Run Code Online (Sandbox Code Playgroud)

歌曲,价格,网址存储在Song模型中.

数据结构:

Artist
- id
- name

Album
- id
- name

Song
- artist_id
- album_id
- name
- price
- url
Run Code Online (Sandbox Code Playgroud)

楷模:

Artist
has_many :songs

Album
has_many :songs

Song
belongs_to :artist
belongs_to :album
Run Code Online (Sandbox Code Playgroud)

我已经找到了Roo并观看了关于Roo的Railscasts.我可以将数据导入一个模型.但我不明白如何同时将数据导入3个模型,避免重复.

此外,我想知道,如果再次上传相同的歌曲,如何更新歌曲的价格和网址.

请解释或说明如何处理多模型数据导入.

我为语法错误道歉,英语不是我的母语.

Ste*_*zyn 5

class Artist
  has_many :albums
  has_many :songs

class Album
  has_many :songs
  belongs_to :artist

class Song
  belongs_to :album
  belongs_to :song
Run Code Online (Sandbox Code Playgroud)

当你遍历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
Run Code Online (Sandbox Code Playgroud)