So, I load the images from a ckeditor, and when I render the html, it does not show, no error appears, just a blank square, instead of the image, I tried raw, html_safe, but it does not solve, the text I put is showing normally, does anyone have any idea why this happens?
a image is in
https://user-images.githubusercontent.com/26804018/31889194-ae1084e8-b7dd-11e7-85c7-1ba09d946269.png
in my view:
<h6><b>1. Objetivo:</b></h6>
<p><%= raw #pop.objective %></p>
my controller:
def show
# redirect_to :index_pdf
# #pop = Pop.friendly.find(params[:id])
#pop = Pop.find(params[:id])
pdf = render pdf: #pop.title,
:layout => false,
template: "pops/index_pdf.html.erb",
locals: {:pop => #pop},
header: {
right: 'Pág. [page] de [topage].'
}
# send_file(pdf, :filename => #pop.title+'.pdf')
# baixar automaticamente
# precisa fazer
end
my model:
has_attached_file :image, styles: { medium: "300x300>" }, default_url: "/images/default.png"
I solved by putting a helper method:
def with_abs_path(htmlstring)
htmlstring.to_s.gsub(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + 'address_of_server' + '\3\2')
end
and calling in a view of my pdf:
<%= raw with_abs_path(#pop.objective) %>
the view was the same show:
<%= raw #pop.objective %>
Related
In Rails 5 app with devise, I need to use a new.js.erb file to update select tag in my registrations view and controller. I cant seem to figure out why my new.js.erb file isn't working.
I've tried to use respond_to in controller as below,
registrations-controller.rb
def new
super
#cities = CS.get(:us,params[:state])
respond_to do |format|
format.js { render '/new.js.erb' }# layout: false }
format.html
end
end
new.html.erb
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), :remote => true) do |f| %>
<div class="signup-input-container">
<div class="field">
<%= f.text_field :firstname, autofocus: true, autocomplete: "firstname", placeholder: "First name", class: "signup-input-container--input" %>
</div>
<div class="field">
<%= f.select :state, options_for_select(CS.states(:us).map { |code, name| [name, code] }),{:prompt => "State"}, {:class => "signup-input-container--input", :id => "state-picker"} %>
</div>
<div class="field">
<%= f.select :city, options_for_select([]),{}, {:class => "signup-input-container--input", :id => "city-picker"} %>
</div>
</div>
<% end %>
new.js.erb
var city = document.getElementById("city-picker");
while (city.firstChild) city.removeChild(city.firstChild);
var placeholder = document.createElement("option");
placeholder.text = "Choose a city";
placeholder.value = "";
city.appendChild(placeholder);
<% #cities.each do |c| %>
city.options[city.options.length] = new Option('<%= c %>');
<% end %>
main.js
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
$.ajax({
url: "/states?state=" + state.value,
type: "GET"
})
})
I'm expecting this to create select tag options with my array of cities in my controller. Does anyone know how to get this to work?
To solve this you should just setup a separate controller where you can fetch the data from asynchronously and alternatively there are also several free API's which can be used for geographical lookup such as Googles Geocoding API and Geonames.
To setup a separate controller you can do it by:
# /config/routes.rb
get '/states/:state_id/cities', to: 'cities#index'
# /app/controllers/cities_controller.rb
class CitiesController < ApplicationController
# GET
def index
#cities = CS.get(:us, params[:state_id])
respond_to do |f|
f.json { render json: #cities }
end
end
end
I would skip using a .js.erb template altogether and just return JSON data which you can use directly in your JS or with one of the many existing autocomplete solutions. .js.erb only makes sense for extensive HTML templating (like for example rendering an entire form) where you want to reuse your server side templates - it greatly increases the complexity and generally makes a mess of your javascript which is not worth it just to output a list of option tags.
// If you are using jQuery you might as well setup a delegated
// handler that works with turbolinks,
$(document).on('change', '#state-picker', function(){
$.getJSON("/states/" + $(this).value() + "/cities", function(data){
// using a fragment avoids updating the DOM for every iteration.
var $frag = $('<select>');
$.each(data, function(city){
$frag.append$('<option>' + data + '</option>');
});
$('#city-picker').empty()
.append($('frag').children('option'));
});
});
I'm looking to extract all records to a single pdf using Prawn PDF and rails 4.2.
Currently I have them generating by id for individual pdf's and works well.
Show
def show
#agreement = Agreement.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = AgreementPdf.new(#agreement)
send_data pdf.render, filename: "Agreement - #{#agreement.entity}", type: "application/pdf", disposition: "inline"
end
end
end
Index in table
<% #agreements.each do |agreement| %>
<tr>
<td><%= agreement.entity %></td>
<td><%= link_to 'Download', agreement_path(agreement.id, format: 'pdf'), :target => "_blank" %></td>
</tr>
<% end %>
First, you have to add a route with the path of the new method:
get '/agreements/all_records' => 'agreements#all_records', :as => :agreement_all_records
Then call the methods with in the view:
<td><%= link_to 'Download All Records', agreement_all_records_path(), :target => "_blank" %></td>
It will look something like this in the controllers:
def all_records
#agreements = Agreement.all
pdf = AgreementsPdf.new(#agreements)
send_data pdf.render,filename:'agreements.pdf',type:'application/pdf', disposition: 'inline'
end
And the Report may look like this ( assuming that agreement model has id,name fields ):
require 'prawn/table'
class AgreementsPdf < PdfReport
TABLE_WIDTHS = [100, 100]
PAGE_MARGIN = [40, 40, 40, 40]
def initialize(agreements=[])
super(:page_size => "LEGAL", margin: PAGE_MARGIN, :page_layout => :landscape)
#agreements = agreements
display_table
end
private
def display_table
if table_data.empty?
text "None data"
else
table(table_data,column_widths: TABLE_WIDTHS, :cell_style => { size: 10 } )
end
end
def table_data
#table_data ||= #agreements.map { |e| [e.id, e.name] }
end
end
Hope this will give you an idea
i want to use avatar through paperclip. in tutorial use gravatar
messages_helper.rb
def recipients_options(chosen_recipient = nil)
s = ''
User.all.each do |user|
s << "<option value='#{user.id}'
data-img-src='#{gravatar_image_url(user.email, size: 50)}'
#{'selected' if user == chosen_recipient}>
#{user.name}</option>"
end
s.html_safe
end
i change on this code and it working.
module MessagesHelper
def recipients_options(chosen_recipient = nil)
s = ''
User.all.each do |user|
s << "<option value='#{user.id}' data-img-src='#{user.avatar.url(:thumb)}'
#{'selected' if user == chosen_recipient}>#{user.username}</option>"
end
s.html_safe
end
end
new.html.erb
<div class="form-group">
<%= label_tag 'recipients', 'Choose recipients' %>
<%= select_tag 'recipients', recipients_options(#chosen_recipient), multiple: true, class: 'form-control chosen-it ' %>
</div>
user.rb
has_attached_file :avatar, :styles => { :medium => "150x150>", :thumb => "30x30#" }, default_url: "https://s3.amazonaws.com/myinstick/logo/instagram-icon.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
But! if user dont have avatar, that use image paperclip default. and it does not scaling and It looks big. how to set the style or size.
it looks like this
in your model:
has_attached_file :avatar,
:styles => { thumb: "100x100#", medium: "300x300#", large: "900x500#"}
or whatever size you want it to be. The # is for cropping. It will select the center of the image and crop the specified height and width from there. You can also just use the default > if you don't want the cropping... and in your view:
<%= image_tag #user.avatar.url(:medium) %>
I solved the problem. Drop-down list uses
jquery.image-select.js
(function($) {
// Image template, this can be overridden from the constructor (options.template),
// must contains {src} placeholder. Ther eare two class names 'chose-image' or 'chose-image-small', modifiy in CSS
var fn_template = '<img class="{class_name} " src="{url}" />';
// Store the original 'chosen' method
var fn_chosen = $.fn.chosen;........
I can set class for all images, like this
var fn_template = '<img class="{class_name} image-circle-minisize" src="{url}" />';
and everything works
I can convert HTML pages into PDF documents well. The problem is, I don't know how to convert the HTML file into a landscape orientation PDF. Is there a way to set that in the controller?
From the controller...
def pdf_customer_shipments
#customer = Customer.find(params[:id])
#shipments = Shipment.where("customer_id = ? AND status = 'Open'", #customer.id)
render :layout => 'pdf'
end
In case this helps, I am using PDFKit and can render the pdf in landscape using:
respond_to do |format|
format.html
format.pdf {
html = render_to_string(:layout => false , :action => "my_page.html.haml")
kit = PDFKit.new(html, :orientation => 'Landscape')
kit.stylesheets << "#{Rails.root}/public/stylesheets/views/pdf.css"
send_data(kit.to_pdf, :filename => "some_name.pdf", :type => 'application/pdf')
return # to avoid double render call
}
end
I got the orientation part from here: https://github.com/pdfkit/pdfkit/issues/12
You need a meta tag in you html file:
...
<head>
<meta name="pdfkit-orientation" content="Landscape"/>
</head>
...
Then the PDF is in landscape orientation.
PDFKit should accept options for wkhtmltopdf, so you should be able to render in landscape mode by using this:
def pdf_customer_shipments
#customer = Customer.find(params[:id])
#shipments = Shipment.where("customer_id = ? AND status = 'Open'", #customer.id
render :layout => 'pdf', :orientation => 'Landscape'
end
I'm getting up to speed on rails and ran into an odd problem. I'm rendering some images from the database (Image models attached to another model, Plants). I'm having some trouble when attempting to do it via a partial. I've got show.html.erb
<fieldset class="fieldset">
<legend>Images</legend>
<%= unless #plant.images.blank? then
for image in #plant.images
debugger
render :partial => 'show_image', :object => image
end
else
"This plant has no images to display."
end
%>
</fieldset>
And the partial _show_image.html.erb:
<div class="image_container">
<% debugger %>
<img src="<%= url_for(:action => 'picture', :id => object.id) %>"/>
<p class='image_caption'><%= object.comment %></p>
</div>
When this is rendered it just renders a "#" for each image, rather than the actual image. It seems to be just rendering the object as a string, as in the source I get:
<fieldset class="fieldset">
<legend>Images</legend>
#<Image:0x242c910>
</fieldset>
When running through the debugger locally:
/Users/*****/dev/plantmanager/app/views/plants/show.html.erb:54
debugger
(rdb:241) image
#<Image id: 40, comment: "Test", name: "Ixia.gif", content_type: "image/gif", data: "GIF89a2\0002\000####$\205\233\tI\250\"x\224\b?\206\031d|ju####\v\031###\247\bI\257G\222\232\222\227\263\262...", plant_id: 55, thumbnail: nil>
(rdb:221) #plant
#<Plant id: 55, name: "Test", description: "Test", created_at: "2009-05-07 07:19:44", updated_at: "2009-05-07 07:19:44", planted: "2009-05-07 00:00:00", sprouted: "2009-05-15 00:00:00", plant_type_id: 1, finished: "2009-05-27 00:00:00">
(rdb:221) #plant.images
[#<Image id: 40, comment: "Test", name: "Ixia.gif", content_type: "image/gif", data: "GIF89a2\0002\000####$\205\233\tI\250\"x\224\b?\206\031d|ju####\v\031###\247\bI\257G\222\232\222\227\263\262...", plant_id: 55, thumbnail: nil>]
(rdb:221) continue
/Users/*****/dev/plantmanager/app/views/plants/_show_image.html.erb:2
<% debugger %>
(rdb:221) object
#<Image id: 40, comment: "Test", name: "Ixia.gif", content_type: "image/gif", data: "GIF89a2\0002\000####$\205\233\tI\250\"x\224\b?\206\031d|ju####\v\031###\247\bI\257G\222\232\222\227\263\262...", plant_id: 55, thumbnail: nil>
(rdb:221) object.id
40
(rdb:221) object.comment
"Test"
(rdb:221) continue
Here are my models [snipped a bit]:
class Plant < ActiveRecord::Base
has_many :images
validates_presence_of :name
validates_presence_of :plant_type_id
validates_associated :images
after_update :save_images
def image_attributes=(image_attributes)
image_attributes.each do |attributes|
# TODO: Probably handle validation in the image model?
if attributes[:id].blank?
unless attributes[:uploaded_picture].blank?
tmpImg = images.build()
tmpImg.uploaded_picture=attributes[:uploaded_picture]
tmpImg.comment = attributes[:comment]
end
else
img = images.detect { |i| i.id == attributes[:id].to_i }
img.attributes = attributes
end
end
end
def save_images
images.each do |i|
if i.should_destroy?
i.destroy
else
i.save(false)
end
end
end
end
class Image < ActiveRecord::Base
validates_format_of :content_type,
:with => /^image/,
:message => "--- you can only upload pictures"
attr_accessor :should_destroy
def should_destroy?
should_destroy.to_i == 1
end
def uploaded_picture=(picture_field)
self.name = base_part_of(picture_field.original_filename)
self.content_type = picture_field.content_type.chomp
self.data = picture_field.read
#image = MiniMagick::Image.from_blob self.data
#self.thumbnail = resize_and_crop(image, 100).to_blob
end
def base_part_of(file_name)
File.basename(file_name).gsub(/[^\w._-]/, '')
end
end
Try this instead:
<% unless #plant.images.blank?
for image in #plant.images
%>
<%= render :partial => 'show_image', :object => image %>
<% end
else %>
This plant has no images to display.
<% end %>
Sorry about the formatting, but you get the idea.
Build a method for the pic in your Image model
class Image < ActiveRecord::Base
belongs_to :plant
validates_presence_of :uploaded_picture
...
end
In your plants controller
def plant_pic
img = Image.find(params[:id])
# THE NEXT LINE IS THE ONE I THINK YOU ARE MISSING:
send_data img.uploaded_picture, :filename =>"plant#{img.plant_id}_#{img.id.to_s}+'.jpg',
:type => 'image/jpeg',
:disposition => 'inline'
end
...
And then in your plants view:
<fieldset class="fieldset">
<legend>Images</legend>
<% if plant.images.blank? -%>
<p>This plant has no images to display.</p>
<% else %>
<%= #plant.images.each do |image| %>
<div class="img_container">
<img src="<%= url_for(:action => 'plant_pic', :id => image.id) %>"/>
</div>
<% end -%>
<% end -%>
</fieldset>
You may want to encode/decode the uploaded_picture binary field someway (I use Base64.encode and Base64.decode) in your images controller, but that's another issue.
Hope that helps you