Export data to a .csv file on ruby app - ruby

I got an error
undefined method `form_for_results_path'
in my code to Export the data to a .csv file. Really don't know if I missed something. Here what I have:
item_controller
def export
CSV.open("result_data.csv", "w") do |csv|
csv << ["cod", "genre", "den_cont"]
end
end
In the view
<%= link_to 'Download CSV', form_for_results_path(#form), :method => :export %>
Thanks

Change it to this and read some more about rails basics.
<%= link_to 'Download CSV', controller: :item, action: :export%>

in your controller, you should do something like this, using rails send_data method:
def export
data = # your data in csv format
options = {
:filename => "some_name.csv",
:type => 'text/csv'
}
send_data(data, options)
end
you can also change your download link using a route_helper. add an entry in your routes file
get 'items/export', :as 'download_items_data"
then your link_to can look like this:
link_to 'Download CSV', download_items_data_path

Related

How to use Simple Form and Direct Upload ActiveStorage

I'm having a trouble when I try to use Simple Form gem for upload video. I'm using ActiveStorage and local storage for this.
My form looks like this:
= simple_form_for #film do |f|
= f.error_notification
= f.input :title, as: :string
= f.input :description, as: :string
= f.input :cover_img, as: :file
= f.input :film_link, as: :file, direct_upload: true
= f.button :submit
= link_to 'back', :back, class: 'btn btn-secondary'
I've followed instruction on here https://edgeguides.rubyonrails.org/active_storage_overview.html
So I've included js and css files in my app. But that won't work. It looks like there's some troubles with passing direct_upload: true via simple_form.
I've also find article https://phase2online.com/blog/2018/10/03/easily-upload-files-with-active-storage-in-rails-5-2/ and pull git repo from here
An this works on when you'll use form_for on your _form. When I change form to use simple_form gem(instead of form_form use simple_form_for) it won't work.
Anyone have an idea why this is not working please?
I use ruby 2.6.3 and Rails 5.2.3 and simple_form (5.0.1)
There're is the way to make this work.
We can change f.input to f.file_field as hashrocket suggest - but then validation of simple form will not work, and perhaps we have to add class to this input plus extra div before.
We can add html attribute to the f.input.
For me this is working I hope it will help someone else too.
= simple_form_for #film do |f|
= f.error_notification
= f.input :title, as: :string
= f.input :description, as: :string
= f.input :cover_img, as: :file, input_html: { data: { direct_upload_url: '/rails/active_storage/direct_uploads' } }
= f.input :film_link, as: :file, input_html: { data: { direct_upload_url: '/rails/active_storage/direct_uploads' } }
= f.button :submit
= link_to 'back', :back, class: 'btn btn-secondary'
These days (rails 6.x), you shouldn't need to specify as: file (simple form should figure this out via reflection) and you can just pass direct_upload: true to input_html:
= simple_form_for #film do |f|
= f.error_notification
= f.input :title, as: :string
= f.input :description, as: :string
= f.input :cover_img, input_html: { direct_upload: true }
= f.input :film_link, input_html: { direct_upload: true }
= f.button :submit
= link_to 'back', :back, class: 'btn btn-secondary'
Verify it's doing the right thing by looking at the generated html. You should see an attribute like this on each input which is of type="file":
data-direct-upload-url="https://<your app server>/rails/active_storage/direct_uploads"
#anka's suggestion to create a custom input type is a good one, but you could also edit the default simple form wrappers for file types if you know all your files will be direct uploads to S3.
I would suggest to simply add a custom input for that to avoid repetition within your view files. Put this in the file app/inputs/direct_upload_file_input.rb:
# frozen_string_literal: true
class DirectUploadFileInput < SimpleForm::Inputs::FileInput
def input_html_options
super.merge({ direct_upload: true })
end
end

Rails 5.2 ActionMailer Mail won't send. Can't see any error in server

Trying to send a volunteering form through SMTP using Gmail, Sendgrid or anything really however I have Action Mailer all set up and I presume I should really be seeing the email come through when I look at the email. I can see this error below but cannot see any error or receive any email at all. I've tried writing puts in my create action but I do not see those either so this is hopefully an easy fix as I'm missing something or have something not follow the usual Rails convention.
I'm using rails 5.2
What I see in the server:
Started GET "/volunteer?utf8=%E2%9C%93&authenticity_token=AZ%2FAflVf%2BlqRUYm45Jo82wAMpq%2B%2BY%2F93piLbeRXdK5n%2FQIWhuaUL3Oe2%2FSwzR%2FCLvj%2FAKW%2BBgD8dPd8vJYRDBA%3D%3D&volunteer_message%5Bname%5D=test+name&volunteer_message%5Bemail%5D=email%40test.com&volunteer_message%5Bphone_number%5D=88888888&volunteer_message%5Bbody%5D=test+email&commit=Send" for 127.0.0.1 at 2018-10-10 17:29:42 +0100
Processing by PagesController#volunteer as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"AZ/AflVf+lqRUYm45Jo82wAMpq++Y/93piLbeRXdK5n/QIWhuaUL3Oe2/SwzR/CLvj/AKW+BgD8dPd8vJYRDBA==", "volunteer_message"=>{"name"=>"test name", "email"=>"email#test.com", "phone_number"=>"88888888", "body"=>"test email"}, "commit"=>"Send"}
Ok so here's my code and the way it's all layed out.
PagesController.rb contains a page called volunteer and this contains the partial (Called _new.html.erb) which is the form which is in it's own folder called volunteer_messages
views/volunteer_messages/_new.html.erb
<%= simple_form_for #volunteer_message, url: create_volunteer_message_url do |f| %>
<%= #volunteer_message.errors.full_messages.join(', ') %>
<%= f.input :name, placeholder: 'name' %>
<%= f.input :email, placeholder: 'email' %>
<%= f.input :phone_number, placeholder: 'phone number' %>
<%= f.input :body, placeholder: 'body' %>
<%= f.submit 'Send' %>
<% end %>
routes created
# is this causing a problem do you think?
get '/volunteer' => 'pages#volunteer'
# volunteer message routes
get '/volunteer', to: 'volunteer_message#new', as: 'new_volunteer_message'
post '/volunteer', to: 'volunteer_message#create', as: 'create_volunteer_message'
models/volunteer_message.rb
class VolunteerMessage
include ActiveModel::Model
attr_accessor :name, :email, :phone_number, :body
# validates :name, :email, :phone_number, :body, presence: true
end
mailers/volunteer_message_mailer.rb
class VolunteerMessageMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.volunteer_message_mailer.volunteer.subject
#
def volunteer(volunteer_message)
#body = volunteer_message.body
#subject = "Volunteer Request sent from www.myapp.com"
mail to: "myemail#example.com", from: volunteer_message.email
end
end
volunteer_messages_controller.rb
class VolunteerMessagesController < ApplicationController
def new
#volunteer_message = VolunteerMessage.new
end
def create
#volunteer_message = VolunteerMessage.new volunteer_message_params
if #volunteer_message.valid?
VolunteerMessageMailer.volunteer(#volunteer_message).deliver_now
redirect_to new_volunteer_message_url
flash.now[:notice] = "We have received your volunteer request and will be in touch soon!"
else
flash.now[:notice] = "There was an error sending your volunteer request. Please try again."
render :new
end
end
private
def volunteer_message_params
params.require(:volunteer_message).permit(:name, :email, :phone_number, :body)
end
end
pages_controller.rb
class PagesController < ApplicationController
def volunteer
#lead = Lead.new
#volunteer_message = VolunteerMessage.new
end
end
development.rb
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
enable_starttls_auto: true,
user_name: 'me#gmail.com',
password: 'gmailapppassword',
authentication: 'plain'
}
Not sure what else I can add here. I do not think I even need he stmp_settings to see action mailer actually show the template of the email being sent?
Also I'm guessing it is somehting to do with the form and the route because ive added puts messages into the create action on the volunteer_message controller and do not see them in my server log.
I'm not getting any errors when pressing submit. I do notice the params going into the url but that's it. it stays there and when refreshes stays on the same screen.
example:
http://localhost:3000/volunteer?utf8=%E2%9C%93&authenticity_token=AZ%2FAflVf%2BlqRUYm45Jo82wAMpq%2B%2BY%2F93piLbeRXdK5n%2FQIWhuaUL3Oe2%2FSwzR%2FCLvj%2FAKW%2BBgD8dPd8vJYRDBA%3D%3D&volunteer_message%5Bname%5D=test+name&volunteer_message%5Bemail%5D=email%40test.com&volunteer_message%5Bphone_number%5D=88888888&volunteer_message%5Bbody%5D=test+email&commit=Send
Is the clue in the server text in the image that shows params going to the pages controller. I do not really want that. Just want the partial to be there but the action to work of the create action in the volunteer_messages controller.
Any help be much appreciated. Thanks.

Download link on Paperclip Attachment in Rails_admin

I am using rails_admin gem together with Paperclip. My model looks like this:
class Product < ActiveRecord::Base
has_attached_file :asset,
:styles => {
:thumb => "100x100#",
:small => "150x150>",
:medium => "200x200" }
validates_attachment_content_type :asset, :content_type => /\Aimage\/.*\Z/
end
How can I include a download link into the index action? So that, on admin/products every entry in the table will have a download link? I read through the documentation, but they don't seem to specify any of these features.
[EDIT]
On my main index action which was routed here: /products I used to do:
<%= link_to "Download", product.asset.url(:original, false) %>
You just need to do.
<%= link_to "Download", product.asset(:original) %>
or
<%= link_to "Download", product.asset.url(:original) %>
They both do the same thing.
If you want to change what version of the image they download just change :original to :medium, :small or :thumb.
For Rails Admin do following:
config.model "Product" do
list do
....
field :download do
formatted_value do
bindings[:view].tag(:a, href: bindings[:object].assets(:original)) << "Download"
end
end
end
...
end
[SOLVED]
Submission model:
class Submission < ActiveRecord::Base
# Image attachment and validations
has_attached_file :file,
:url => "/files/:class/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/files/:class/:attachment/:id/:style/:basename.:extension"
validates_attachment_content_type :file, :content_type => 'application/pdf'
end

convert embedded ruby file to PDF file instead of only HTML file using Rails 3

I want to convert my embedded ruby file to PDF file after clicking on a link using Rails 3.I became able to convert simple html file to PDF file using pdfkit gem.I am explaining my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
#html = render_to_string(:action => "/users/download_pdf.html.erb")
#kit = PDFKit.new('http://google.com')
#kit = PDFKit.new(html)
#send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
kit = PDFKit.new("<h1>Hello</h1><p>This is PDF!!!</p>", :page_size => "A4")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
#file = kit.to_file('my_file_name.pdf')
end
end
In this controller page i did and got success to convert from HTML to PDF.
users/index.html.erb:
<p>
<%= link_to "Download pdf",download_pdf_path(:format => 'pdf') %>
</p>
When user will click on the above "download_pdf" link the download.html.erb will convert to PDF file and it should display as well as download in specified folder.The download.html.erb file is given below.
users/download.html.erb:
<h1>Hello Rails</h1>
The above file should convert into PDF file with proper css .If i have css for this like below.
application.css:
h1{
width:100px;
height:100px;
background-color:red;
}
How can i include this CSS in that PDF file.My other files are given below.
pdfkit.rb:
PDFKit.configure do |config|
#config.wkhtmltopdf =Rails.root.join('bin', 'wkhtmltopdf-i386').to_s
config.wkhtmltopdf='C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
#config.default_options[:ignore_load_errors] = true
end
Please help me to resolve this issue and make this successfully.
By using wicked_pdf gem i am getting the following error.
error:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/wkhtmltopdf/bin/wkhtmltopdf.exe", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-3204-59mbli.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
check the below code for this gem.
users/users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
render pdf: 'test',
layout: '/layouts/test',
template: '/users/test',
handlers: [:erb],
formats: [:pdf],
:save_to_file => Rails.root.join('public', "test.pdf")
end
end
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
}
You can include your stylesheets by following:
def download_pdf
kit = PDFKit.new(File.open(Rails.root.join('app', 'views', 'users', 'download.html.erb')))
kit.stylesheets << Rails.root.join("app","assets","application.css")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
end

How to download search results of index page using axlsx?

First, I am really sorry if this question is too trivial. I am new with rails and couldn't figure out where i am doing it wrong.
I have a model named Costing and in it's index page i have a search form. I am trying to use 'axlsx' gem to download only the search results but I always get all the rows. I am also using 'will_paginate' gem.
Here is my code.
//costings_controller.rb
def index
#costings = Costing.search(params[:search] , params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #costings }
format.xlsx {
send_data #costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet"
}
end
end
// index.html.erb
<%= link_to 'Download Costings', url_for(:format=>"xlsx") %>
Please help me here.
Thanks a lot in advance.
Here is the code that I made for a demo of axlsx gem. Browse through it and implement your requirement in the controller. Here is the output of this demo.
//costings_controller.rb
def download
#costings = Costing.search(params[:search] , params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #costings }
format.xlsx {
send_data #costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet"
}
end
end
// index.html.erb
<%= form_for :costing, url: download_costing_index_path do %>
...
<% end %>
//routes
resources :costing do
collection do
post :download, :defaults => { :format => 'xlsx' }
end
end

Resources