Ruby on Rails read csv file and fill table

Asked

Viewed 566 times

1

I have following table news :

create_table "noticia", force: true do |t|
    t.integer  "conteudo_id"
    t.integer  "entidade_id"
    t.integer  "imagem_id"
    t.string   "texto"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

and I have the following a. csv file containing these fields in the following format:

Texto_post, url image

I would appreciate a help on how to read the file and also if necessary it is possible to change the layout of the contents of the file.

  • table name in Rails is plural, "news"

  • In this case . csv doesn’t have all the data to create the object, right? how will you do with relationships?

  • Conteudo.create(titulo: data[0])
 conteudo_id = Conteudo.order("created_at").last.id
 Imagem.create(imagem_url: data[2])
 imagem_id = Imagem.order("created_at").last.id
 Noticium.create(conteudo_id: conteudo_id,entidade_id: data[1], imagem_id: imagem_id, texto: data[3])

1 answer

1


  • Where do I put this code ? It’s my first project with ruby on Rails and I’m not very comfortable..

  • you can put in the db/Seed.Rb file, to run the Seed just type in the db:Seed rake.

  • It depends on how you use @Carlosmachado. How will your app receive this . csv? Is it via upload? Or the file is on disk and will only be loaded 1x?

  • @Alextakitani the file is always on disk

  • @Carlosmachado crie uma rake task: http://railscasts.com/episodes/66-custom-rake-tasks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.