Prawn + Prawnto Issue - ruby-on-rails

I know prawn is working because I have a show action that if I add .pdf on to the end of it loads show.pdf.prawn. However, I have a form:
<%= form_tag(:controller => "/holders", :action=> "generate", format: "pdf") do %>
<%= label_tag(:count, "How Many Students?") %>
<%= text_field_tag(:count) %>
<%= hidden_field_tag :holder_id, value: #holder%>
<%= submit_tag("Generate Course Lesson") %>
<% end %>
That submits count to the the generate action.
Inside my generate action I have the following:
def generate
prawnto :filename => "print.pdf"
respond_to do |format|
format.html
format.pdf { render :layout => false}
end
end
and my generate.pdf.prawn looks like:
pdf.text "HELLO WORLD"
When I submit the form I get the URL: http://localhost:3000/generate.pdf and Chrome tells me
Failed to load PDF document with no other errors or information.
I noticed I am getting: Rendered holders/generate.pdf.erb in my dev logs which indicates its not even looking for the .prawn file.
What am I doing wrong?

Setup your action like this:
def generate
respond_to do |format|
format.html
format.pdf { prawnto :filename => 'print.pdf' }
end
end

Related

How to render flash messages when remote true

I have a time logger controller method that calls from my view, called _embed_menu.html.erb
<%= link_to l(:start_time_logger) + ' #' + #issue.id.to_s + ' ',
{:controller => '/time_loggers', :action => 'start', :issue_id => #issue.id},
:class => 'icon icon-start',
:"data-replace" => '#time-logger-menu',
:remote => true
%>
The part of 'start' method, where I shown an error:
respond_to do |format|
format.js{ flash[:error] = l(:start_time_expired_error)}
end
Now to the part of the rendering flash messages. application_helper.rb
Have render_flash_messages function.
def render_flash_messages
s = ''
flash.each do |k,v|
s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
end
s.html_safe
end
and that function called on base.html.erb template.
<%= render_flash_messages %>
So the result - I launch a start method and flash shown only after I reload the page. I also tried to redirect with the hope that after this redirect the error will show.
redirect_to controller: 'issues', format: 'js'
but no result.
Maybe I can trigger re-rendering of <%= render_flash_messages %>?
What happens when you click a remote: true link is that Rails creates a request for text/javascript and then runs the resulting javascript in that page.
Usually a js.erb template contains some javascript that modifies the document:
$("<%= escape_javascript(render #user) %>").appendTo("#users");
So if you want to alter the flash messages on the page you need to target the wrapping element and append it:
$("<%= escape_javascript(render_flash_messages) %>").appendTo("#flashes");
This assumes you have a wrapping element around the flash messages. Otherwise just add one to the layout.
<div id="flashes">
<%= render_flash_messages %>
</div>
Use flash.now[:error] if you need to use the flash message on the same request.
https://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now
https://guides.rubyonrails.org/action_controller_overview.html#flash-now
replace flash to flash.now.
for example,
respond_to do |format|
format.js{ flash.now[:error] = l(:start_time_expired_error)}
end
and in js.erb file re-render the partial where you want to update.
I just manually redirect to the page by window.location solution - here I just call issues index controller, but here can any link.
flash[:error] = l(:start_time_expired_error)
respond_to do |format|
format.js{ render js:"window.location='/issues/"+#issue.id.to_s+"'"}
end

Rails 4 - how to make a link to a PDF file (name.PDF)?

I am generating PDF files and my link look like this:
<%= link_to 'Invoice', display_invoice_path(invoice.id), :format => :pdf %>
When I click on this, it takes me to /display_invoice/123456789 (it's an HTML version).
In the controller action is following:
def display_invoice
if params[:invoice_number]
#invoice = ...
respond_to do |format|
format.html
format.pdf do
#render pdf: '123', # file name
render pdf: params[:invoice_number],
layout: 'layouts/application.pdf.erb'#, # layout used
#show_as_html: params[:debug].present? # allow debuging
end
end
end
end
and in the routes:
get '/display_invoice/:invoice_number', to: 'invoices#display_invoice', :as => 'display_invoice'
After clicking the link, I'd like to have in the URL /display_invoice/INVOICE_NUMBER.pdf - currently, there's just /display_invoice/INVOICE_NUMBER.
How to open it with the ".pdf" suffix?
Thank you.
You need to add the pdf mime type.
Add the following line to the file config/initializers/mime_types.rb:
Mime::Type.register "application/pdf", :pdf
See http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads for details.
EDIT:
The format needs to be part of the path helper:
display_invoice_path(invoice.id, :format => :pdf)
use this code instead of your code
<%= link_to 'Invoice', display_invoice_path(invoice.id, :format => :pdf) %>
There is a new syntax without using Hash Rocket
<%= link_to "Invoice", display_invoice_path(invoide, format: :pdf), target: "_blank" %>
If you want to have URL in anchor tag then use .._url instead of .._path
<%= link_to "Invoice", display_invoice_url(invoide, format: :pdf), target: "_blank" %>

Returning javascript from controller without action specific js file

So the way that I've been taught initially to implement ajax in my rails apps is to create a js file for each action per controller, and then reference that js file within the respond_to block.
This is really annoying, and I like to include all my javascript in a single main.js file isntead of compartmentalizing every snippet.
This has been working nicely so far, except for when I want to pass an object to the proper function.
Here is how I'm supposed to handle the ajax request to create a new user listing in my app:
<%= form_for #client, action: :create, remote: true do |f| %>
<%= f.text_field :firstname, placeholder: 'First Name' %>
<%= f.text_field :lastname, placeholder: 'Last Name' %>
<%= f.hidden_field :status, value: true %>
<%= submit_tag :create %>
<% end %>
.... form gets the remote: true tag.
def create
#client = current_trainer.clients.create(client_params)
respond_to do |format|
format.html { redirect_to clients_path }
format.js
end
end
.... create action passes response to default create file:
$('.active').prepend("<%= j render #client %>");
That's all fine and dandy. But I don't like this setup. I want to make a call like this instead:
def create
#client = current_trainer.clients.create(client_params)
respond_to do |format|
format.html { redirect_to clients_path }
format.js { render js: "theApp.clientsPage.saveClient();" }
end
end
.... and then in the main.js.erb file I have:
saveClient: function() {
$('.active').prepend("<%= j render #client %>");
},
BUT the error I'm getting is the following:
undefined method `render' for #<#<Class:0x007fd278f350c8>:0x007fd27b182298>
main.js.erb including only in layout I think, yes? Then it compiles on launch (for example this form on your main#index action) index action and you have no #client.
Just give an argument to saveClient function, like this:
saveClient: function( newElement ) {
$( ".active" ).prepend( newElement );
},
And then in create action call:
format.js { render js: "theApp.clientsPage.saveClient( $( \"<div>#{ j render #client }</div>\" ) );" }

suryveyor gem how to output the survey in pdf?

I read about the surveyor gem and in the webpage http://nubic.github.io/surveyor/
Where do I put this line to export the survey report to a pdf?
%li= link_to "PDF", view_my_survey_path(:survey_code => response_set.survey.access_code, :response_set_code => response_set.access_code, :format => 'pdf')
I am not understanding please help.
From the looks of the website that you supplied you should have generated the surveyor:custom controllers. From this it then tells you to install the two following gems
gem 'pdfkit'
gem 'wkhtmltopdf'
But personally I prefer to use wicked_pdf in my opinion. So slightly changing the tutorial a little I would do the following:
rails generate surveyor:custom
This will generate the controllers. So then we can later configure this using the options that wicked_pdf will supply us.
Add the following lines to your Gemfile:
gem 'wicked_pdf' #https://github.com/mileszs/wicked_pdf
gem 'wkhtmltopdf' #https://code.google.com/p/wkhtmltopdf/
In order to have wicked_pdf export correctly you need to have something like this inside an action in your surveyor controller that is generated for you. So you may have something like this in your index action of your surveyor_controller.rb
respond_to do |format|
format.html
format.pdf do
render :pdf => "Survey Report",
:header => {:html => {:template => 'layouts/pdf.html.erb'}}
end
end
From this respond block you could/should I think have the following directory in views - app/views/survey/index.html.erb Inside the index.html.erb you would then have your above link inside this.
<%= link_to "PDF", view_my_survey_path(:survey_code =>
response_set.survey.access_code, :response_set_code =>
response_set.access_code, :format => 'pdf') %>
I have never used the surveyor gem before. But based upon what you have supplied, and what you want I have tried to give as much of a detailed explanation as I can. Hope this potentially helps you or anyone else
Example of Wicked_PDF usage
def index
#bookings= Booking.scoped
booking = #bookings
#user = current_user
if params[:format] == 'pdf'
#bookings= #bookings.where(:day => Date.today.beginning_of_month..Date.today.end_of_month)
end
respond_to do |format|
format.html
format.pdf do
render :pdf => "#{Date.today.strftime('%B')} Overtime Report",
:header => {:html => {:template => 'layouts/pdf.html.erb'}}
OvertimeMailer.overtime_pdf(#user, booking).deliver
end
end
end
View.html.erb
<%= Link_to "Overtime", "booking.png", bookings(:format => "pdf") %>
In order to generate the PDF you need to create a file which has the following extension .pdf.erb what this means is that when the link is processed it processes the embedded ruby code first and then outputs PDF. So in this case I want to do bookings. So I did created in my views/bookings/index.pdf.erb inside this I have the following:
views/bookings/index.pdf.erb
<br />
<% #bookings.each do |booking| %>
<p>
<b>Employee</b>
<%= booking.user.try (:full_name)%>
</p>
<p>
<b>Hospital</b>
<%= booking.hospital.try(:name)%>
</p>
<p>
<b>Day</b>
<%= booking.day.to_s(:long_ordinal) %>
</p>
<p>
<b>Overtime</b>
<%= booking.overtime %>
</p>
<br />
<% end %>
<h2>Total Overtime is <b><%=#bookings.to_a.sum(&:overtime)%></b></h2>
This should give you some core grounds to work off of

where does render :partial html end up

I have a view with an ajax form:
<%= form_tag( {:action => 'some_action'}, {:remote => true}) do %>
...
<%= submit_tag "Submit" %>
<% end %>
Now, in the target action, I want to display a partial
def some_action
# some logic
render :partial => "some_partial"
end
The partial is just html. _some_partial.html.erb could be
<br>Hi, this is the partial</br>
When I submit the form, I see the html response packet is received in the browser (with firebug's net logs), but the html doesn't show up anywhere. Where should the html be? How to render a partial html view from an action?
you are rendering a partial but not specifying where to render it.
in rails 2 you could do it with:
def some_action
# some logic
render :update do |page|
page.replace_html 'some_div_id', :partial => 'some_partial'
end
end
but in rails 3, above code is no longer valid.
see Unobtrusive Javascript
create a file named some_action.js.erb and write the code in it:
// update div with id some_div_id
$("#some_div_id").html("<%= escape_javascript(render :partial => 'some_partial') %>");
in controller
def some_action
# some logic
respond_to do |format|
format.js
end
end
I figured out how to send and display html. From theReq, just add :remote => true, "data-type" => "html" to the form and then in the javascript of the page, capture the returned html on ajaxSuccess to display it:
$('form#whatever').on('ajaxSuccess', function (event, data, status, xhr) {
$('div#target').html(data);
}
)

Resources