Carla Dessi
Carla Dessi

Reputation: 9666

Saving form results to a text file in Rails

I have this form:

<%= form_tag(:action => "save", method: "post") do %>
  <%= label_tag(:email, "Email") %>
  <%= text_field_tag(:email) %>
  <%= submit_tag("Submit") %>
<% end %>

I need to save the results into a file, I'm currently using CSV but it doesn't really matter what the file type is:

def save

  require "csv"
  CSV.open "output.csv", "a+" do |csv|
    csv << [ "#{params[:email]"]
  end
  render :none
  redirect_to "/thanks"
end

And in my routes I have:

get 'form', to: "static_pages#form"
get 'form/submit', to: "static_pages#save"
get 'form/thanks', to: "static_pages#thanks"

At the moment the CSV is generated but the parameters don't save to it, and also it dosesn't redirect, I just get 404 not found on /submit

Upvotes: 0

Views: 309

Answers (1)

Marcin Adamczyk
Marcin Adamczyk

Reputation: 509

Your form and routes are incorrect. <%= form_tag('/form/submit') %> Default method is POST so you dont have to specify it.

Routes should be changed according to method: post 'form/submit', to: 'static_pages#save'

PS: I believe you should go RESTful, but I dont see full picture of your application.

PPS: You shouldnt do render when you are redirecting.

PPPS: Dont require 'csv' inside your method, but on the very beginning of file, before your class definition.

Upvotes: 2

Related Questions