I am writing a script that allows for a user to pass a format via a URL parameter. I have JSON and XML working as needed, but I can't get YAML working.
case params[:format]
when "xml" then respond_with(#labels)
when "json" then respond_with(#labels_hash.to_json)
when "yaml" then render :text => #labels_hash.to_yaml
end
For some reason when I pass the format=yaml in my URL then my script tries to force download a file. Any reason why this would happen?
Working Code:
case params[:format]
when "xml" then respond_with(#labels)
when "json" then respond_with(#labels_hash.to_json)
when "yaml" then respond_with(#labels_hash) do |format|
format.yaml { render :text => #labels_hash.to_s }
end
end
Try:
Adding :yaml to respond_to :yaml in the controller, and :
respond_to do |format|
....other formats....
format.yaml { render :yaml => #labels_hash }
end
Related
I can :include assiciations to json-response using to_json like so:
def stats
#orders = Order.all
respond_to do |format|
format.json { render :json => #orders.to_json(:include => :review) }
end
end
It works okay, but what if I need associations on multiple variables?
This:
def stats
#orders = Order.all
#tasks = Task.all
respond_to do |format|
format.json { render :json => {
orders: #orders.to_json(:include => :review),
tasks: #tasks.to_json(:include => :user)
}
}
end
end
is not working – it's returning a string instead of json:
You can try this. see the following example
e.g.
ActiveSupport::JSON.decode(orders)
To decode the Json string in to Hash.
This is the situation where the jbuilder kicks in, which comes as a default ruby gem in Rails 4
I'm having a problem in Sinatra where I can't respond with just a json and I can't find good sinatra docs anywhere, most of things seems outdated.
Anyways, here's the code:
module MemcachedManager
class App < Sinatra::Base
register Sinatra::Contrib
helpers Sinatra::JSON
get '/' do
json({ hello: 'world' })
end
end
end
MemcachedManager::App.run! if __FILE__ == $0
The response that I do get is:
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><p>{\"hello\":\"world\"}</p></body></html>\n"
Where it should have been only the json part. Why is it rendering html tags when I didn't ask for it?
Have you seen this blog post?
require 'json'
get '/example.json' do
content_type :json
{ :key1 => 'value1', :key2 => 'value2' }.to_json
end
I would also modify this to:
get '/example.json', :provides => :json do
to stop HTML/XML calls using the route. Since you're using the sinatra-contrib gem, and since Ruby doesn't need all those parens etc, you can also simplify the code you've given as an example to:
require 'sinatra/json'
module MemcachedManager
class App < Sinatra::Base
helpers Sinatra::JSON
get '/', :provides => :json do
json hello: 'world'
end
end
end
MemcachedManager::App.run! if __FILE__ == $0
Try putting
content_type :json
before the json(...) call
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
I am using rails 2.3.2
I have a link_to_remote functions
<%= link_to_remote "Comments ", {
:url => {:controller => "blogs",:action => "fetchcomments",:id => blog.id}} %> |
and the rails action as
def fetchcomments
unless params[:id].nil?
#blog = Blog.find(params[:id])
respond_to do |format|
format.js do
render :update do |page|
page.replace_html("comm", 'hi')
end
end
end
end
The above code throws me the error as
try {
Element.update("comm", "hi");
} catch (e) { alert('RJS error:\n\n' + e.toString());
alert('Element.update(\"comm\", \"hi\");'); throw e }
Please give me suggestions
Remove unless params[:id].nil? and it will work if you have an element with the id 'comm' on the page that makes the request. Of course it will replace whatever is inside with the word 'hi'.
I got this Rails3 action:
def export
respond_to do |format|
format.tdl { render :xml => #template.export_as_tdl and return }
format.json { render :json => #template.export_as_json }
end
end
and filter before the export:
def find_environment
#environment = KTEnvironment.find(params[:environment_id])
raise HttpErrors::NotFound, _("Couldn't find environment '#{params[:environment_id]}'") if #environment.nil?
#environment
end
and this rspec:
describe "export" do
it "should call export_as_json" do
#tpl.should_receive(:export_as_json)
get :export, :id => TEMPLATE_ID
end
it "should call export_as_tdl" do
#tpl.should_receive(:export_as_tdl)
get :export, :id => TEMPLATE_ID, :format => 'tdl'
end
end
I also defined the following MIME type:
Mime::Type.register "application/tdl-xml", :tdl
When I try to run my rspec tests, I am constantly getting:
1) Api::TemplatesController export should call export_as_tdl
Failure/Error: get :export, :id => TEMPLATE_ID, :format => 'tdl'
AbstractController::DoubleRenderError:
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
# ./app/controllers/api/api_controller.rb:135:in `render_exception'
# ./app/controllers/api/api_controller.rb:133:in `render_exception'
# ./app/controllers/api/api_controller.rb:22:in `__bind_1314974553_619675'
# ./spec/controllers/api/templates_controller_spec.rb:178
I have no clue what is happening there. This is my exception rendering code:
def render_wrapped_exception(status_code, ex)
logger.error "*** ERROR: #{ex.message} (#{status_code}) ***"
logger.error "REQUEST URL: #{request.fullpath}"
logger.error pp_exception(ex.original.nil? ? ex : ex.original)
orig_message = (ex.original.nil? && '') || ex.original.message
respond_to do |format|
format.json do
render :json => {
:errors => [ ex.message, orig_message ]
}, :status => status_code
end
format.all do
render :text => "#{ex.message} (#{orig_message})",
:status => status_code
end
end
end
Ah so the render_exception general method in my api_controller is called. It looks like:
def render_exception(status_code, exception)
logger.error pp_exception(exception)
respond_to do |format|
format.json { render :json => {:errors => [ exception.message ]}, :status => status_code }
format.all { render :text => exception.message, :status => status_code }
end
end
Try disabling your error handler, the root cause should come up on its own.