What is the `.html` used in ruby on rails? - ruby-on-rails

I see lots of code snippets that goes:
respond_to do |format|
format.html { something }
format.json { something }
end
I'm wondering what the html and json are in the above code snippet. Are they methods? Scopes? Attributes?

Let's investigate, shall we? This is implementation of respond_to:
def respond_to(*mimes)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
collector = Collector.new(mimes, request.variant)
yield collector if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
_set_rendered_content_type format
response = collector.response
response ? response.call : render({})
else
raise ActionController::UnknownFormat
end
end
(the documentation is quite thorough, by the way. Check it out.)
We see that it yields some Collector to the block (which you refer to as format). Here it is: https://github.com/rails/rails/blob/0e70595acc8796c3e0854ef72df478d597243e68/actionpack/lib/abstract_controller/collector.rb
We see that it just enumerates all Mime content types and generates (dynamically) methods for them. Oh and JFYI, here are all the possible things you can respond_to:
Mime::SET.map(&:symbol)
=> [:html,
:text,
:js,
:css,
:ics,
:csv,
:vcf,
:png,
:jpeg,
:gif,
:bmp,
:tiff,
:mpeg,
:xml,
:rss,
:atom,
:yaml,
:multipart_form,
:url_encoded_form,
:json,
:pdf,
:zip,
:doc,
:excel]

Related

Ruby On Rails - Pass parameters from front end to database through controllers

How to pass parameters from front end to back-end API in Ruby on Rails only through controllers? I do not want to use model or views for this.
I am using a Ruby Gem which captures some usage data which needs to be stored into the back end database.
I have created a controller, to which the post parameters are sent, but I get an error saying view is not found.
ActionView::MissingTemplate (Missing template usage_metrics/create, application/create with {:locale=>[:en], :formats=>[:json, :js, :html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :web_console_v2], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
* "/home/local/www/cc2/cc_user-frontend/app/views"
* "/home/local/.rvm/gems/ruby-2.2.3/gems/ckeditor-4.2.2/app/views"
):
You need to send the request in an appropriate format (i.e. json) and ensure the controller action responds to this. At the moment it's trying to respond with html but not finding a template for this.
For example, in the action, after you've done what you need to do:
respond_to do |format|
format.json { render json: { whatever: is_needed_in_the_response } }
end
And you'll get your response that way.
Or if you don't need a response after parsing the params, you can use render nothing: true.
N.B. I think the newest versions Rails will respond with nothing / json if there's no template found. Not sure how this affects you.
Hope that helps!
if you want to return some data as json you can use
render json: data
but if you only want to return status
render json: {}, status: 200

Rails Template is missing render json

actually i use rails for my REST API, and i need transform my object to json but when i try i got this error:
<h1>Template is missing</h1>
<p>Missing template firms/show, application/show with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=>[:erb, :builder, :arb, :jbuilder]}. Searched in:
* "/Users/allan/Desktop/Work/back/app/views"
* "/Library/Ruby/Gems/2.0.0/gems/activeadmin-0.6.0/app/views"
* "/Library/Ruby/Gems/2.0.0/gems/kaminari-0.16.3/app/views"
* "/Library/Ruby/Gems/2.0.0/gems/devise_invitable-1.5.5/app/views"
* "/Library/Ruby/Gems/2.0.0/gems/devise-3.5.4/app/views"
</p>
This is my code
def show
firm= Firm.find_by_subdomain(params[:subdomain])
if firm.present?
respond_to do |format|
#firm = firm
format.json { render :json => #firm.to_json }
end
end
end
I hope someone here can help me :)
Solve:
def show
render json: Firm.find_by_subdomain(current_subdomain)
end
thank you
Template missing means that you asking for a html view, not doing a json request.
If you want to always return json format regardless of format param, do this:
before_action :set_default_response_format
protected
def set_default_response_format
request.format = :json
end
#source: Rails 4 - How to render JSON regardless of requested format?
Try to add .json at the end of you query when querying your route. Without this, it will try to render html and it will go search for view file that might not be present in your case.

Rendering a view of controller action from around_action callback

I'm rendering a js.erb partial which enables ajax functionality to like/dislike a restaurant dish. I recently came across the around_action callback and figured yield would help perform the controller action first and render the template second. Unfortunately I'm getting a 500 (Internal Server Error) due to the respond_to never getting called.
The respond_to method works if I place it inside the controller action but not inside the callback. What am I doing wrong?
class DishesController < ApplicationController
before_action :set_dish_and_restaurant
around_action :render_vote_partial
def like
#dish.liked_by current_user
end
...
private
def set_dish_and_restaurant
#dish = Dish.find(params[:id])
end
def render_vote_partial
yield
respond_to { |format| format.js { render "vote.js.erb" } }
end
end
Console Error
ActionView::MissingTemplate (Missing template dishes/like, application/like with {:locale=>[:en], :formats=>[:js, "application/ecmascript", "application/x-ecmascript", :html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
* "/app/views"
* "/Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/app/views"
):
app/controllers/dishes_controller.rb:29:in `render_vote_partial'
Okay so with your stack trace it is pretty clear what is happening. You have to understand the default rails behavior of convention over configuration.
As soon as you call yield, your controller action gets called. Now all controller actions by default look to render views with the same name as action, once the actions are done executing.
So calling render_to after yield doesn't make any sense, as controller action you yielded to has already called its render :)
In any case what you are trying to do is a bad design pattern, rendering views should be left to actions
Update
Theoretically speaking : As you wish to keep things DRY you could render the same view after each action by creating a common method calling it after every action. However, think about it, your render will have one line, and calling that same method will need one line too :) so where's the DRY.
In short, DRY should not be over done at the cost of simplicity. In my opinion KISS trumps DRY :)

Using render in RSpec view test

I'm using RSpec to test my views. I want to test that the view for the edit action contains a field (or text) "Director". It's choking on render. Here's my code:
# spec/views/movies/edit.html.haml_spec.rb
require 'spec_helper'
describe 'movies/edit.html.haml' do
it 'displays \'director\' field on edit page' do
render
expect(rendered).to have_content("Director")
end
end
On running this I get the following error:
Failure/Error: render
ActionView::Template::Error:
No route matches {:action=>"show", :controller=>"movies", :id=>nil}
My understanding is that convention over configuration means that render without any arguments should render the intended view app/views/movies/edit.html.haml I don't know why it's looking for the route to the action show. That route does exist, though it has nothing to do with this spec.
I've tried a number of permuations of arguments to render with no luck:
render :edit
render action: :edit # is this even valid?
render :action => :edit
render "edit"
render "edit.html.haml"
render action: "edit"
render action: "edit.html.haml"
render :action => "edit"
render :action => "edit.html.haml"
All the above produce one of two errors:
ArgumentError:
You invoked render but did not give any of :partial, :template, :inline, :file or :text option.
OR
ActionView::MissingTemplate:
Missing partial /edit, movies/edit with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=>[:erb, :builder, :coffee, :haml]}.
I'm not trying to render a partial, I'm trying to render the full view. Am I using the convention incorrectly, or using render incorrectly?
Edit1: I don't think it's a partial. There is a view at app/views/movies/edit.html.haml. I may not properly understand what a partial is.
Edit2: I tried the same spec for the new action and it seems to run fine (fails when the text is not there, passes when the text is there). Does this mean I need to load the edit view as a partial, or do I need to give it dummy data for #movie? And why is edit a partial?
For anyone else looking for something similar, you should be assigning a movie model for the view to render.
Something like the following should work:
describe 'movies/edit.html.haml' do
let(:movie) { Movie.create(movie_params_go_here) }
it 'displays \'director\' field on edit page' do
assign(:movie, movie)
render
expect(rendered).to have_content("Director")
end
end

Missing template action error in rails3

I have defined a method in controller that is like:
def self.dailymail
.... #fill data from db
ac = ActionController::Base.new()
kit = PDFKit.new(ac.render_to_string(:action => "formatinhtml.html.erb",:rawdata => data))
pdf = kit.to_pdf
... #send pdf in mail
end
formatinhtml is like:
def formatinhtml
#dailyrep = params[:rawdata]
respond_to do |format|
format.html # daily.html.erb
end
end
I have to use self.dailymail so that I can call it from model & in turn from rufus scheduler.But,still I get error such as:
scheduler caught exception:
Missing template action_controller/base/daily.html with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :xls], :handlers=>[:erb, :builder, :coffee]}. Searched in:
* "F:/DEVELOPMENT/TrackIt/app/views"
C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.8/lib/action_view/path_set.rb:58:in `find'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.8/lib/action_view/lookup_context.rb:109:in `find'...
so,what does I need to do?
Update: After debugging,I found action formatinhtml is not actually being getting called;I have defined neccessary routes.
Your folder where "daily.html" is located is not the same as your controller

Resources