jeudi 9 avril 2015

Ruby on Rails: read user submited .txt file into variable

I'm building a ruby on rails app that lets the user pick a file from their hard drive, and then writes specific lines from the text file into a database. I've built the form, but now I don't know how to get the content of the file into a variable, format it and then write it into the database.


I have a database table named drafts with colums set_1, set_2, set_3. I want to write line 13(from the text file) into set_1, line 165 into set_2 and line 317 into set_3. I also want to format the lines before writing them. In the file they look like this ------ FRF ------ and I only want FRF.


I've spent a lot of time searching stackoverflow and rubyonrails guides but have a hard time figuring this out. I'm very new to ruby and rails in general, so any help is appreciated.


Here's my controller:



class DraftsController < ApplicationController
def new
@page_title = "Upload MTGO Draft"
@draft = Draft.new
end

def create
@draft = Draft.new(draft_params)
if @draft.save
flash[:notice] = "Draft Saved!"
redirect_to drafts_show_path
else
render "new"
end
end

def index
@page_title = "MTGO Draft"
end

def show
@page_title = "MTGO Draft Replayer"
end

def search
@page_title = "Search MTGO Draft"
end

def destroy

end

private
def draft_params
params.require(:draft).permit(:name)
end
end


and my new.html.erb:



<%= form_for @draft do |f| %>
<div class="form-group">
Draft Name:<%= f.text_field :name, class: 'form-control' %><br />
<%= f.submit "Create" %>
</div>
<% end %>

<%= form_for @draft do |f| %>
<div class="form-group">
Draft Log: <%= f.file_field :file %>
</div>
<% end %>


If you need more info or want to get into the whole app more he's a gitHub repository.


Thanks for the help.


Aucun commentaire:

Enregistrer un commentaire