ActionController::UnknownFormat in HelpController#about - ruby-on-rails

as a Ruby newbie I am still getting to grips with the language. I have created a broadcast controller for a simple database that is already being used in production. However, I am getting the above mentioned error. Below is the code I have used:
show.html.erb
<p id="notice"><%= notice %></p>
<%= link_to 'Edit', edit_broadcast_path(#broadcast) %> |
<%= link_to 'Back', broadcasts_path %>
Index.html.erb
index.html.erb
broadcasts_controller.rb
boradcast controller
help controller
class HelpController < ApplicationController
skip_before_action :authenticate_user!
def about
#render text: "Hello"
end
end
I am not sure if I am missing any files or configs, I will add them in the comments if need be. Thanks

Incoming requests may use headers or parameters to indicate to Rails what format, called "MIME type", the response should have. For instance, a typical GET request from entering a URL into your browser will ask for an HTML (or default) response. Other types of common responses return JSON or XML.
In your case your "about" action does not have any explicit responders, and because of that Rails can't match the requested format (which is what the error message is trying to convey). You will probably just want to add an HTML template app/views/help/about.html.erb with your content. Rails should identify the HTML template and handle things from there.
More info
In Rails you need to respond with a specific format, and it is easy to setup your controller actions to handle a variety of formats.
Here is a snippet you might find in a controller which can respond in 3 different ways.
respond_to do |format|
format.html { render "foo" } # renders foo.html.erb
format.json { render json: #foo }
format.xml { render xml: #foo }
end
You can see more examples and deeper explanations in the documentation here.
ActiveRecord helps because it comes with serializers out of the box which can create JSON and XML representations of your objects.

Related

ActionController::UnknownFormat in Controller ( #index)

I have a link_to calling my #index. In this method lies a respond_to for a format.js so I can initiate some Ajax. Things is, when I look at the console I get an error 500 because of a "ActionController::UnknownFormat"
I have tested out differents solutions from older posts, but I can't figure out what I'm missing.
controler :
def index
respond_to do |format|
format.js { render partial: 'private/messages/load_more_messages' }
end
end
view :
<%= link_to "Load messages", private_messages_path(:conversation_id => conversation.id), remote: true %>
Does anyone have any thoughts on this ? It's supposed to be a text book case, but I've been hitting my heads against a brick wall with this one.
If you are loading a HTML partial try it like this:
def index
render partial: 'private/messages/load_more_messages'
end
Although i would recommend making a specific endpoint for fetching partials that you pass a route to since this might be something you do frequently in a project.
Something like this
def render_partial(partial_route)
render partial: partial_route
end
Well, after going around testing a wide range of ideas, I came back to my original thought and it worked perfectly. I don't know what went wrong the first time but now it is perfect.

Rails: action and views

My question is : do we need a view file for each action in our controller?
(like if we defined a say_hello action in a controller, is it necessary to add say_hello.html.erb in his view directory?
I'll edit this to say it depends (with same content). If you plan on using that controller action as JS or JSON you don't need a view file. if you want one to share in multiple views, the file can contain a shared partial (which can be used in other views). This examples is shown by the generators scaffolding create examples like this. They are helpful if you are learning rails. Not great otherwise.
If you were to share a partial, you could have a partial named _form.html.erb and then inside your say_hello.html.erb file, it would just call:
<%= render 'form' %>
If you want to render JSON or JS files you can respond_to in your action:
respond_to do |format|
format.html # say_hello.html.erb
format.json { render json: #hello } #no file needed
format.js { render js: #hello }
#format.js   {} #do nothing... or use a little javascript in there...
# or have a file named say_hello.js.erb and use your #hello variable
end
Edit:
One last update. Your say_hello.js.erb file can do the anything on another view (if called remotely):
say_hello.js.erb
<% if #hello.attribute == "some value" %>
$('#div_in_another_view').show();
<% else %>
$('#div_in_somewhere_else').hide();
<% end %>
You can do jQuery and anything you want to the view calling it (as long as it's using AJAX).
End edit
Guides are great place to get started. Railscasts.com as well (even though Ryan isn't updating anymore).
Edit: A great example on the different options on the respond_to is on this rails guide regarding javascript
You can just pass javascript straight from that format.js call, or use a file if you need more complicated stuff. You don't need to do anything also. You could just have it return xml or nothing as well, depending on your use case.
No, it is not required. For example, you can render json or xml data from the controller without needed a view at all. This article explains it very well http://guides.rubyonrails.org/layouts_and_rendering.html
No you do not need a view for each action. BUT you do need a view for each action that will reach the end of the method.
If you return anywhere in the action then you are fine. A view is only required when an implicit render is called due to execution reaching the end of the action.
No, it's really up to you and it depends on what the action will actually do. Actions can render different types content types: text, json, html, xml... etc. Here's an example:
def show
render xml: #something
end
This action doesn't have a view, but it'll output an xml when called. It can also render different things based on the format of the call:
def show
respond_to do |format|
format.html do
redirect_to '/'
end
format.json do
render xml: #something
end
end
end
The action may also redirect (again, this one doesn't have a file):
def show
redirect_to '/'
end
At the end, it's really up to the programmer to handle how the action behaves, but if you leave it empty, it'll assume there's a file to render.

How to POST to the external sites form from rails controller with redirecting to this external site at the same time?

I heve mysite.com (rails app) and there is not mine site other.site.com
There is the form on the other.site.com to which I want to put some data. The data is not sensitive (not a login/pass/...) but it is not working via GET.
So I need to gather data in my controller and redirect user to the form at the other.site.com filling this form at the same time.
I do not need to submit this form, I just need to fill it and leave it up to user to submit the form or not.
Use form_tag helper:
<%= form_tag 'url_where_you_want_to_POST' %>
... your form controls
<% end %>
More information about this helper you can read in the rails api reference.
you can use JSON to send data:
site 1:
inside controller
def action1
#say you want send a #data
respond_to do |format|
format.json { render :json => #data }
end
end
site 2:
now get this data and generate a form
def action2
#data_from_site1 = Net::HTTP.get(URI.parse("http://example.com/action1.json")) #or you can use html format
#parse_data = JSON.parse #data_from_site1
# now use this #parse_data inside the View of this action
end
I hope you are looking for this.

How to use Rails respond_with with a create action and javascript?

I've been reading about respond_with. and used it before in a couple of tutorials but dont really think I understand it fully.
The functionality I am trying to implement right now is this: I have a list of items of class Article, and each of them has a link to the create Favorite action. When the user clicks on it it the favorite instance is created and the user is redirected to the home page. I want this to work with AJAX without a page refresh, and execute some JavaScript on the article item to let the user know it's been favourited successfully. I've used the :remote => true attribute in the relevant link, so the action is executing remotely without problem, but I am a bit stuck on how to execute the action's .js.erb file.
I've done the following in the controller:
class FavouritesController < ApplicationController
before_filter :authenticate
respond_to :html, :js
def create
#article = Article.find_by_id(params[:article_id])
current_user.Favourites.create(:article => #article)
redirect_to root_path
end
The problem is, I dont know what parameter should i pass to respond_with. I've tried replacing the redirect with both respond_with #article, and respond_with without parameters, and while both of them work (the create.js.erb is called), I dont understand why...
I dont want to 'respond_with' anything, but only that when the action is executed via javascript, the create.js.erb gets called. Can anyone explain a) why does respond_with work anyway whatever I pass to it, and b) what is the right way to do this?
BTW, I am using Rails 3.0
EDIT: I understand it better if I use respond_to like in the following code, but I would like to understand respond_with better.
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
I ran across this question several times trying to solve a similar problem. It turns out my controller wasn't inferring the format as I assumed it would from the content type or the fact that it's an xhr request.
In any case, it worked when I switched from this:
contacts_path
To this:
contacts_path format: :json
I didn't care for that per se, so I changed my ajax call to include the dataType option like this (per jQuery ajax documentation):
$.ajax({url: contactUrl, type: 'POST', data: data, dataType: 'json' });
Hi Oalo go through the link below, it concisely explains the respond_with and respond_to. It lists all the options that you can pass to respond_with
http://ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with
Hope this answers your query

Redirecting to a 500 page when an AJAX call fails in Ruby on Rails

I'm working with an application built in Ruby on Rails with very poor error handling right now. If a controller method is executed via ajax, and that method results in a 500 (or 404 or any other response) the 500.html page is rendered and returned as the result to the AJAX request. Obviously the javascript doesn't know what to do with that HTML and the web page looks like it's just waiting for a response.
Is there an easy way in rails to render an error.rjs template anytime an error occurs during an AJAX call?
You can use respond_to inside a controller's rescue_action or rescue_action_in_public method. Consider the following controller:
class DefaultController < ApplicationController
def index
raise "FAIL"
end
def rescue_action(exception)
respond_to do |format|
format.html { render :text => "Rescued HTML" }
format.js { render :action => "errors" }
end
end
end
I solved a similar problem with authorization. I created a simple authorization controller with this action:
def unauthorizedxhr
render :update do |page|
page.replace_html("notice", :partial=>"unauthorizedxhr")
page.show("notice")
end
end
Here's the template:
<% if flash[:notice] -%>
<div id="noticexhr"><%= flash[:notice] %></div>
<% end -%>
When the authorization failed in the controller, I'd redirect to the :controller=>"authorization", :action=>"unauthorizedxhr" after setting the flash[:notice] value. This allowed me to customize the message I sent to the user, and it handled the display of the message through the render :update code above.
You could adapt this to your problem by creating an errors controller, catching any raised errors in your other controllers, then simply redirecting to :controller=>"errors", :action=>"displayxhr" when the call fails. That way, you'll have standardized your error communication mechanism but allowed yourself the ability to customize error messages by each action.
You can still use cpm's idea above, but the error's display will be handled by separate and distinct controller logic. that should make it a little easier to maintain.
Hope that helps.
-Chris
This was my final solution:
def rescue_action_in_public(exception)
response_code = response_code_for_rescue(exception)
status = interpret_status(response_code)
respond_to do |format|
format.html { render_optional_error_file response_code}
format.js { render :update, :status => status do |page| page.redirect_to(:url => error_page_url(status)) end}
end
end
This basically forwards to the correct static HTML page no matter if the request was via AJAX or normal GET/POST.
This is NOT used for normal error handling like validation etc. It's only used when something really bad happens - like an unhandled exception.
You can do like below :
in allpication.js
$(document).ready(function(){
$(document).ajaxError( function(e, xhr, options){
if("500" == xhr.status)
{
$(location).attr('href','/users/sign_in');
}
});
})
Its working for me.....

Resources