I am trying to generate a pdf from a view in jruby on rails using flying saucer with the following code in the controller:
def calendar
#patient = Patient.find_by_id(params[:id])
result = render_to_string
send_data( FlyingSaucer::create_pdf(result), :filename => "calendar.pdf",
:type => "application/pdf",
:disposition => 'attachment')
end
I am getting an error
uninitialized constant PatientsController::FlyingSaucer
I am requiring java and flying_saucer in the controller
any help would be appreciated
Try this:
require 'flying_saucer'
java_import org.xhtmlrenderer.pdf.ITextRenderer
class SomeController < ApplicationController
def show
respond_to do |format|
format.pdf { send_data render_pdf, :filename => 'test.pdf' }
end
end
private
def render_pdf
io = StringIO.new
content = render_to_string(:layout => false)
# content = '<html><body><h1>Yo</h1></body></html>'
renderer = ITextRenderer.new
renderer.set_document_from_string(content)
renderer.layout
renderer.create_pdf(io.to_outputstream)
io.string
end
end
end
Try looking at slide 66 of this presentation for an example.
This might also be of help.
Ensure the flying saucer jars are in the classpath.
Related
I have a controller that render a json with data from models. When i enter route to get it it do nothing and just show and error in console.
Controller:
class Api::ForecastController < ApplicationController
before_action :set_hourly_forecast, only: %i[ show edit update destroy ]
def index
respond_to do |format|
format.html do
#hourly_forecasts = HourlyForecast.where(forecast_location_id: params[:forecast_location_id]).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
end
format.json do
weather_service = WeatherService.where(name: params[:name])
#forecast_location = ForecastLocation.where(weather_service_id: weather_service)#& municipality: #municipality.name)
#hourly_forecasts = HourlyForecast.where(forecast_location_id: forecast_location.id ).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_hourly_forecast
#hourly_forecast = HourlyForecast.find(params[:id])
end
# Only allow a list of trusted parameters through.
def hourly_forecast_params
params.require(:hourly_forecast).permit(:forecast_location_id, :date, :temperature, :humidity, :rain, :rain_probability, :wind_speed, :wind_direction)
end
end
Error:
> Started GET "/api/forecast.json?name=dark_sky" for 127.0.0.1 at 2022-04-20 18:33:29 +0200
Processing by Api::ForecastController#index as JSON
Parameters: {"name"=>"dark_sky"}
No template found for Api::ForecastController#index, rendering head :no_content
Completed 204 No Content in 53ms (ActiveRecord: 6.2ms | Allocations: 4983)
The route i use its
127.0.0.1:3000/api/forecast.json?name=dark_sky
So the output should be a json with all hourly model.
But it just do nothing and on console it does get and the select but jumps this error of template, i dont understand it since im new on rails.
If need more controllers, models or anything ask in comments.
You have to have a separate template file to render json index.json.jbuilder for example.
# app/views/api/forecasts/index.json.jbuilder
json.array! #hourly_forecasts do |hourly_forecast|
json.extract! hourly_forecast, :id, :forecast_location_id, :date, :temperature, :humidity, :rain, :rain_probability, :wind_speed, :wind_direction
json.url api_forecast_url(hourly_forecast, format: :json)
end
https://github.com/rails/jbuilder
If you don't need to customize rendered json too much, render json inline in the controller
format.json do
weather_service = WeatherService.where(name: params[:name])
#forecast_location = ForecastLocation.where(weather_service_id: weather_service)#& municipality: #municipality.name)
#hourly_forecasts = HourlyForecast.where(forecast_location_id: forecast_location.id ).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
render json: #hourly_forecasts
end
https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json
https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
I'm trying to build a JSON API end point with Ruby on Rails.
I followed the instruction in the following and was able to create JSON API for my models
http://railscasts.com/episodes/350-rest-api-versioning?view=comments/
I have the following controller:
/api/v1/movies_controller.rb
class MoviesController < ApplicationController
def index
if params[:p].nil?
p = 1
else
p = params[:p].to_i
end
#movies = Movie.order("id DESC").page(p)
end
def show
#movie = Movie.find(params[:id])
end
end
I need to join this with the Genre object where Movie has_many :genres, and Genre belongs_to :movie
However, I'm not able to use the following to get the genres joined with the movie object for the JSON output:
#movie = Movie.find(params[:id], :joins => :genres)
I did notice that the following command is able to generate the joined output in ruby console
#movie.to_json(:include=>:genres)
But then adding this in the controller doesn't show the additional genres fields
Can someone help me please?
Thanks!
My advise: Go with active_model_serializers
Add the following line to your Gemfile
gem 'active_model_serializers'
Do a bundle install afterwards.
After that do a
rails g serializer movie
rails g serializer genre
Than customize the following code:
/api/v1/movies_controller.rb
class MoviesController < ApplicationController
respond_to :json
def index
if params[:p].nil?
p = 1
else
p = params[:p].to_i
end
#movies = Movie.order("id DESC").page(p)
respond_with #movies
end
def show
#movie = Movie.find(params[:id])
respond_with #movie
end
end
app/serializers/movie_serializer.rb
class MovieSerializer < ActiveModel::Serializer
embed :ids, :include => true
attributes :id, :name
has_many :genres
end
app/serializers/genre_serializer.rb
class GenreSerializer < ActiveModel::Serializer
embed :ids, :include => true
attributes :id, :name
end
Have a look at the full documentation of active_model_serializers at
https://github.com/rails-api/active_model_serializers
I have my Report model:
class Report < ActiveRecord::Base
belongs_to :user
attr_accessible :ready_status, :document
mount_uploader :document, DocumentUploader
def attach( report_file )
self.update_attributes( :document => File.open( report_file ), :ready_status => true )
end
end
This model has attach metod, which i use to save document and other param. Now i want to test that this function works.
/spec/models/report_spec.rb
# encoding: utf-8
require 'spec_helper'
describe Report do
before(:each) do
#user = User.make!
end
...
context "File's saving" do
before(:each) do
#report = #user.reports.create
#csv_report_file = "#{Rails.root}/spec/files/report.csv"
end
it "CSV should be saved" do
csv_report_filename = #csv_report_file.split("/").last
#report.attach #csv_report_file
#report.reload
#report.document.file.filename.should == csv_report_filename
end
end
end
When i try to saving file from /spec/files i get such error:
Report File's saving CSV should be saved
Failure/Error: #report.document.file.filename.should == csv_report_filename
NoMethodError:
undefined method `filename' for nil:NilClass
But when i try another file from another folder (for example "#{Rails.root}/samples/my-report.csv") then my test passes.
How can i fix that?
Oh, i found the answer. Carrierwave doesn't save empty file and i had one. When i added some data in the file (/spec/files/report.csv) my problem has gone.
I have in my application a few controllers that i want to use as a api. In this api i need to use versioning.
in my routes.rb i`m using this:
require 'api_constraints'
(...)
scope '/:target/:version', :module => :api, :constraints => { :version => /[0-z\.]+/ } , :defaults => { :format => 'json' } do
scope :module => :v1, :constraints => ApiConstraints.new(:version => 1, :default => true) do
match '/list' => 'sample#list'
end
end
my api_constraints.rb:
class ApiConstraints
def initialize(options)
#version = options[:version]
#default = options[:default]
end
def matches?(req)
#default || req.headers['Accept'].include?("application/waytaxi.api.v#{#version}")
end
def self.version
#version
end
end
in my SampleController.rb:
module Api
module V1
class SampleController < ApiBaseController
def list
render json: Model.find_by_id(params[:id])
end
end
end
end
the ApiBaseController:
module Api
class ApiBaseController < ApplicationController
before_filter :authenticate
skip_before_filter :verify_authenticity_token
private
def authenticate
# if params[:target] == "ios"
# render :json => {status: 404}
# return false
# end
end
end
end
the problem is:
whenever i try to call Model i get this error:
uninitialized constant Api::V1::SampleController::Model
If i use: ::Model i get this error:
uninitialized constant Model
And yes, i do have this models on my database. If i use Model.all outside the SampleController i get the objects.
P.S.: I'm using rails 3.2.8
Found my problem.
My Model was in plural and on my controller i was calling it in singular
I have a collection of #clients with attributes id and email
I want to render this json format
[
{"id":" 1","label":"johndoe#yahoo.com","value":"1"},{"id":" 2","label":"paulsmith#gmail.com.com","value":"2"}
]
in clients_controller I defined the following method
def search
#clients = Client.where(:user_id => current_user.id).select('id','email')
render :partial => "clients/search"
end
and here is the view _search.json.erb
[
<%= raw #client.map{|client| '{"id":"' +" #{client.id}" +'","label":"' + "#{client.email}" + '","value":"' +"#{client.id}" +'"}' }.join(",") %>
]
this is working, but I found it fugly...is there a more elegant way to generate a custom json format in a view?
Use a helper function you call from the view to format the output or a library function you call from the controller. Example (of later):
def search
#clients = Client.where(:user_id => current_user.id).select('id','email')
respond_to do |format|
format.html
format.json do
render :json => custom_json_for(#clients)
end
end
end
private
def custom_json_for(value)
list = value.map do |client|
{ :id => " #{client.id}",
:label => client.email.to_s,
:value => client.id.to_s
}
end
list.to_json
end
You just need use the to_json method. In you case it's
#client.to_json(:only => [:id, :label, :value])
You could use jBuilder gem from GitHub
for clients_controller
def search
#clients = Client.where(:user_id => current_user.id)
end
and search.json.jbuilder
json.id #clients.id
json.label #clients.email
json.value #clients.id
For more info you can visit Jbuilder on RailsCast
You can use https://github.com/dewski/json_builder/ to customize your json response in the view and separate it from the controller. It's good when you need to add some "current user" depending attributes like
[{:attending => event.attending?(current_user)}]