Add Virtual attribute to active record object to output - ruby-on-rails

I have a custom method in my model called "file_url(:thumb)" to receive a specific thumbnail file URL. The method is provided by the carrierwave gem.
It is not stored in my database. How can I add this virtual attribute to #document so when I convert to json it's included?
module Api
module V1
class DocumentsController < ApiController
respond_to :json
def show
#document = Document.find(params[:id])
respond_to do |format|
format.json { render json: #document }
format.xml { render xml: #document }
end
end
end
end
end

You would need to define your own as_json method in the Document model. Something like this would do the trick:
def as_json(options = { })
h = super(options)
h[:thumb_url] = file_url(:thumb)
h
end

Related

FInding error developing API in Rails

I juts start with the developing of an API using RAILS. Im doing a simple example of my own but I have an error when I want to see the result in my API.
Controller:
class EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
end
end
In controllers/api/energy_calc_controller.rb
class Api::EnergyCalcController < ApplicationController
def index
render json: #data_hash_gen
end
end
Routes
Rails.application.routes.draw do
namespace :api do
resources :energy_calc
end
get 'energy_calc/index'
Views/energy_calc/index.html.erb
<h1>EnergyCalc#index</h1>
<p>Find me in app/views/energy_calc/index.html.erb</p>
<%= #data_hash_gen %>
In the view is printing me the data normally. But when I tried to access: http://localhost:3000/api/energy_calc.json I got null
Any idea?
Put your EnergyCalcController index methods code in to Api::EnergyCalcController's index method. Like this,
class Api::EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
render json: #data_hash_gen
end
end
You don't need to have two different controllers for rendering different formats.It is redundant.You could render HTML and JSON both in a single action.
class EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
respond_to do |format|
format.json {
render :json => #data_hash_gen
}
format.html {
#Objects exclusively needed to render html
}
end
end
end

How do I override Kaminari pagination when rendering JSON in the respond_to block?

I want to override Kaminari's pagination when rendering JSON, or tell it to return all with pagination.
In App1, I am using ActiveResource to access App2's Group model:
class Group < ActiveResource::Base
self.site = "http://www.app2.com:3000"
end
Here's App2's Group model:
class Group < ActiveRecord::Base
default_scope order('name asc')
paginates_per 10
This is my controller. The Group.search stuff is ransack:
class GroupsController < ApplicationController
# GET /groups
# GET /groups.json
def index
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #groups }
end
end
I've added eleven groups to App2. In the console of App1 I get:
[45] pry(main)> Group.all.count
=> 10
What is the best way to do this without changing the HTML pagination rendering?
You can prepare all the common logic you need but only apply pagination for the HTML format:
def index
#search = Group.search(params[:q])
#groups = #search.result
respond_to do |format|
format.html { #groups = #groups.page(params[:page]) }
format.json { render :json => #groups }
end
end
You can run different code in different formats:
def index
respond_to do |format|
format.html {
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
} # index.html.erb
format.json {
render json: Group.all
}
end
end

rails 3 sending view_context to Prawn

I'm trying Prawn to generate pdf's, following this RailsCasts
If I tried the next code, it works fine:
pdf = OrderPdf.new(#order)
But, if added "view_context"
pdf = OrderPdf.new(#order, view_context)
I got this error: "SyntaxError in xxxController#index"
syntax error, unexpected ',', expecting ')'
I tried put in my controller helper_method :view_context but the error still.
Enviroment: rails 3.2.5
My Controller:
def show
#liquidacion = Liquidacion.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #liquidacion }
format.pdf do
pdf = LiquidacionPdf.new (#liquidacion, view_context)
send_data pdf.render, filename: "liquidacion_#{#liquidacion.anio.to_s()+''+#liquidacion.mes.to_s().rjust(2,'0')+''+#liquidacion.numeroliquidacion.to_s()}", type: "application/pdf", disposition: "inline"
end
end
end
And my classPDF:
class LiquidacionPdf < Prawn::Document
def initialize(liquidacion, view)
super(top_margin: 20, :page_layout => :landscape)
#liquidacion = liquidacion
#view = view
numero_liqui
nombre_usuario
lineas_liqui
total_liquidacion
firmas
end
How I writte this?
Your initialize method should accept two parameters. I am guessing that you still only have one it.
Change your initialize method to the below
def initialize(order, view)
super(top_margin: 70)
#order = order
#view = view
order_number
line_items
end
EDIT
take off parenthesis or empty space
respond_to do |format|
format.html # show.html.erb
format.json { render json: #liquidacion }
format.pdf do
pdf = LiquidacionPdf.new #liquidacion, view_context

Rails how to change attribute name when rendering json?

In my controller I have:
#pakkes = Pakke.where("navn like ?", "%#{params[:q]}%")
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #pakkes }
format.json { render :json => #pakkes.map(&:attributes) }
end
How do I change the attribute navn to name when rendering JSON?
You can do this with a one-line method in Pakke:
def as_json(*args)
super.tap { |hash| hash["name"] = hash.delete "navn" }
end
Calling super will generate json hash as usual, then before it's returned you'll swoop in and change the key of the "navn" entry.
Override the as_json method. It's used by to_json in order to produce the output. You can do something like:
def as_json options={}
{
name: navn,
.... # other attributes you want to add to json
}
end

How do you render hashes as JSON in Rails 3

I found how to render ActiveRecord objects in Rails 3, however I cannot figure out how to render any custom objects. I am writing an app without ActiveRecord. I tried doing something like this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
format.json { render :json => {'ok'=>true} }
end
end
When you specify a respond_to, then in your actions you would make a matching respond_with:
class AppControlls < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash)
end
end
It looks like you're conflating the old respond_to do |format| style blocks with the new respond_to, respond_with syntax. This edgerails.info post explains it nicely.
class AppController < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash.as_json)
end
end
You should never use to_json to create a representation, only to consume the representation.
format.json { render json: { ok: true } } should work
This was very close. However, it does not automatically convert the hash to json. This was the final result:
class AppControlls < ApplicationController
respond_to :json
def start
app.start
respond_with( { :ok => true }.to_json )
end
end
Thanks for the help.
For those getting a NoMethodError, try this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
render json: { :ok => true }
end
end

Resources