How do I pass layout false inside respond_to block in Rails? - ruby-on-rails-3

I'm trying to figure out how to make this work. Here is my code, which is not working right now:
respond_with(#addresses) do |format|
format.json {render :json=>#addresses, :layout=>false}
end

The :layout parameter shouldn't be necessary when you're rendering json, xml, etc.

Related

No route matches {:action=>"show", :controller=>"restaurants"}

If I want to go with my home page clicking on the map localhost:3000/maps gets out this error No route matches {:action=>"show", :controller=>"restaurants"}
controllers/maps_controller.rb
def index
#maps = Map.all
#json = Map.all.to_gmaps4rails do |map, marker|
marker.infowindow info_for_restaurant(map.restaurant)
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #maps }
end
end
def show
#map = Map.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #map }
end
end
private
def info_for_restaurant(restaurant)
link_to restaurant_path do
content_tag("h2") do
restaurant.name
end
end
end
routes.rb
resources :restaurants
resources :maps
This is answer for my question:
controllers/maps_controller.rb
def index
#maps = Map.all
#json = Map.all.to_gmaps4rails do |map, marker|
marker.infowindow render_to_string(:partial => "/maps/maps_link",
:layout => false, :locals => { :map => map})
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #maps }
end
end
views/maps/_maps_link.html.erb
<div class="map-link">
<h2><%= link_to map.restaurant.title, map.restaurant %></h2>
</div>
You referred to restaurant_path within info_for_restaurant, which is part of MapsController. Rails met error here.
You need to either define the restaurant_path in restaurant controller, or comment out this function in maps controller at this moment.
Your approach is wrong in several levels. Let's work on them, one at a time:
1) Your call to the route helper is wrong:
restaurant_path is the route helper for a show action. A show action needs an id parameter to be valid. Your call is missing a parameter.
So, your code must be something like this:
def info_for_restaurant(restaurant)
link_to restaurant_path(restaurant) do
content_tag("h2") do
restaurant.name
end
end
end
To see the parameters needed for each action, you can run rake routes on the console.
However, this does not solve the problem, as you're also:
2) Calling view helpers from your controller
link_to and content_tag are view helper methods, and you don't want to bother your controller with view issues. So, the best way to solve this problem is to move your info_for_restaurant method to a helper, and call it from a view instead.
So, now, your controller will not assign anything to #json, and the last line of your view will look like this:
<%= gmaps4rails #maps.to_gmaps4rails {|map, marker| marker.infowindow info_for_restaurant(map.restaurant) } %>

Rails 3 - set the filename in a respond_to

This seems like it should be simple, but I can't seem to find a straight answer.
I have added a csv mime-type, and the following seems to work, except that the downloaded file is always named "report.csv".
In my controller:
def report
respond_to do |format|
format.html
format.csv do
render :template => "summary/report.csv.erb",
:filename => "foo" #doesn't work
end
end
end
I think it's using the default renderer (I haven't implemented an alternate renderer), but I can't seem to find complete docs on the options available.
Isn't there something like a "filename" option or something that I can use? Is there a better approach?
I got it, thanks to some help from this answer.
format.csv do
response.headers['Content-Disposition'] = 'attachment; filename="' + filename + '.csv"'
render "summary/report.csv.erb"
end
First you set the filename in the response header, then you call render.
(The template param to render is optional, but in my case I needed it.)
You can pass the filename to send_data and let it handle the Content-Disposition header.
# config/initializers/csv_support.rb
ActionController::Renderers.add :csv do |csv, options|
options = options.reverse_merge type: Mime::CSV
content = csv.respond_to? :to_csv ? csv.to_csv : csv.to_s
send_data content, options
end
# app/controllers/reports_controller.rb
respond_to do |format|
format.html ...
format.csv { render csv: my_report, filename: 'my_report.csv' }
end
Then add a to_csv method to my_report or pass a pre-generated CSV string.
Alternatively you can use a combination of send_data and render_to_string (since you have a CSV template).
def report
respond_to do |format|
format.html
format.csv do
send_data render_to_string(:template => "summary/report.csv.erb"),
:filename => "foo"
end
end
end

How to render JSON in Rails view

I've tryed the solution of following example: In Rails, how do you render JSON using a view?
But my problem is that the database already has a JSON string saved, I pull the json string and then I should be able to display the JSON file in the the view.
I'm using this because an android tablet should be able to visit the same url but depending on its settings (send by a POST) a different JSON file should be displayed, the android tablet then fetches the json and use it to configure some options.
So I already have a full working json file, i'm looking for a way to display it in a view (without rendering html tags and other stuff). I tryed the following (yes I've added respond_to :json) :
# def show_json (#config is the record, #config.json_config is the actual json configuration file
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json
end
Then my view I have
#show_json.json.erb
<%= #config.config_json %>
Then the HTML I get to see (no errors are given)
<html><head><style type="text/css"></style></head><body></body></html>
Thanks!
EDIT
I'm using rails 3.2.3
Here is my routes (only relevant parts)
match '/events/config', to: "events#show_json", as: :show_json
resources :events do
member do
get :select_item
get :category
end
end
Then also the controller (partial)
respond_to :html, :json, :js
def show_json
#terminal_id = params["mac"]
terminal_id = "3D:3D:3D:3D:3D:3D"
event = current_user.events.where("date(endtime) > ? AND date(starttime) < ?", Time.now.to_s, Time.now.to_s).first
if event.nil?
# Nothing got returned so we use the default event
event = current_user.events.where('"default" = ?', true).first
end
logger.info "MAC: #{terminal_id}"
terminal = current_user.terminals.where(serial: terminal_id).first
logger.info "Terminal: #{terminal.attributes.inspect}"
logger.info "#{event.attributes.inspect}"
#config = event.et_relationships.where(terminal_id: terminal).first
logger.info "CONFIG #{#config[:config_json]}"
respond_to do |format|
format.json { render json: #config[:config_json] }
end
end
Use render:
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json { render json: #config }
end
And then you have path /:model/:action.json.

not able to load a view when I disable javascript rails 3

Here is my controller code:-
def image_test
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to image_test_path}
end
end
I have got a partial by the name of _image_test.html.erb and and a simple view image_test.html.erb
In my routes I have done this:-
match "/image_test", :to => "/index#image_test"
It works fine when the javascript is enabled in the borwser however when I disable the javascript I want it to redirect me to my image_test.html.erb file. Instead I get a no route match error.
Please help me with this.
Thanks,
I created a workaround for this solution which is giving the desired result of redirecting to another page if javascript is disabled in a browser but I do not know if this is the rails way.
I created empty action corresponding view for those actions and redirected to those views in case javascript is disabled.
Here is an example of what I did :-
def javascript_enabled_view
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to :action => "javscript_disabled_view"}
end
end
I have got a corresponding js.erb file and the partial for the above action which will work if javascript is enabled in the browser.
def javascript_disabled_view
end
I have got the corresponding html.erb file which will work in case javascript is disabled in the browser.
Thanks,

Render YAML in Rails 3

Is there anyway to respond_to a .yml file extension?
I have tried, but can't get it to work.
respond_to do |format|
format.xml # index.xml.builder
format.yml {render :text => #labels.to_yaml, :content_type => 'text/yaml'}
end
The above code spits out the following error uninitialized constant Mime::YML
no need to add that stuff to environment.rb, just change format.yml to format.yaml and it will work.
Try to add this into your environment.rb file :
Mime::Type.register 'text/yaml', :yaml