Ruby On Rails: 404 Handle via standard way - ruby-on-rails

Would it be a good idea to add an standard internal 404 page (not in public but in app/view/shared/ folder). A page where user can move to other existing pages via menu / links etc.
Many good websites allow user to browse their site menu on 404. i.e. If in you login into facebook and click some 404 facebook page. YOu will see feeds chats with 404.
Well, In rails I don't know How to do this. well, I google-ed on it.
and What I found (Should be done to handle 404):
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
What I currently have :
render :text => 'User not found', :status => 404`
What I want to do : (if its not bad solution of handling 404):
render :file => '/view/shared/404.html.erb', :status => 404
Please suggest!

Try rendering like:
render "shared/404", :status => 404
I haven't tried it but from what's said in Two controllers for one shared view in Ruby on Rails answer, this might work.

Related

rails add css class if the page has a 404 status

Is there a way in Rails to add a class to a html tag if the current page rendered a 404 error.
On a controller of mine, if a user visits the wrong website it renders a file in the public error with a 404 error like this
else
render file: 'public/error', status: 404, formats: [:html]
end
I want to add a class to my footer, hidden, to hide the footer if this page is rendered. I've tried this with no luck (but it was more of a guess)
<%= "hidden" if current_page?(status: 404) %>
Any suggestions??
You could make it more generic and set an #variable to tell the footer to hide. So if later on you want a 500 page without footer you can use the same trick.
controller
else
#hide_footer = true
render file: 'public/error', status: 404, formats: [:html]
end
view
<%= "hidden" if #hide_footer %>
And you don't need to change anything else.
You could just render a separate layout for your error files
else
render :template => "shared/404", :layout => 'errorlayout', :status => 404
end
You might want to have a look at these questions and answers as well:
Dynamic error pages in Rails 3
how to remove header and footer from some of the pages in ruby on rails
How to hide footer layout on a particular page? - This is basically Ismael Abreu suggestion and is probably the easiest.

Rails Controller -- just return the processed data (dont load into a view)

I'm new to Ruby and Rails. I just completed a course in Laravel, so I am aware of the MVC system(not a newbie as far as the basic concepts are concerned).
I have a rather simple question,
I am sending a POST request to my RAILS REST API,the body of the post request contains a json encoded string like this--->
Array ( [method] => POST [timeout] => 45 [redirection] => 5 [httpversion] => 1.0 [blocking] => 1 [headers] => Array ( ) [body] => {"post_content":"here is the post","post_title":"here we are ","post_author":"1"} [cookies] => Array ( ) )
As you can see,its coming from my php based blog.
My rails API is supposed to be taking the post content and automatically adding links to certains words, by comparing the words with some stuff that i have in an SQLite database.
Ok, so my problem is this:
I just want the response from the Rails controller, I dont want anything loaded into a view. The Rails Controller - returns the content, with 'a href' tags around words that are found in my database. This is to be sent back as the response to my post request, and i want to access it directly as the body of the response.
As of now I dont know how this is to be done. Laravel has the ability to 'return' whatever you want to , at the end of the Controller Action, but in Rails, everything seems to want to load into a view.
I have researched some questions here and found one which said 'render :nothing => true',but that renders nothing at all.Here is what my code looks like.
def process
content = params['post_content']
##perform db function and get back the content with the links embedded.
##HOW TO RETURN THIS CONTENT.
end
Personally, I think, i have to use the render_to_string method, but I have no idea how to do this.
Any help is appreciated.
Best Regards,
Richard Madson.
Some options to consider:
Render just the raw string as the http response body:
render :text => content
Render a view without the default surrounding layout:
render :layout => false
In that case your view could just be:
<%= #content %>
Or render the content as json:
render :json => { :content => content }
The question is, what do you want returned? Text? XML? JSON?
I'm going to assume you want JSON back based on the JSON going in.
respond_to do |format|
format.json { render json: #someobject }
end
It might be helpful to see the rest of the controller method.
If I understand correctly believe what you are looking for is
render :text => "response"
there is also - JSON, XML, nothing, js, file, etc - more information here http://guides.rubyonrails.org/layouts_and_rendering.html

How do you call a model's show url from a Rail create controller?

I'm having trouble calling a model's show path from within a create controller.
I'm using the Koala gem in a Rails 3.2 app. I'm trying to publish to Facebook's open graph automatically when a User creates a particular record type.
I have a page set up with all the required FB meta tags.
I can run the Koala methods from the console and everything works fine.
But if I try to run this from the controller I get an error.
My controller looks like this:
def create
#fb_model = current_user.fb_models.build(params[:fb_model])
if #fb_model.save
Koala::Facebook::API.new(app_token).put_connections( current_user.fb_uid, "namespace:action", :object => fb_model_url(#fb_model) )
respond_to do |format|
format.html { redirect_to(#fb_model, :notice => 'Successfully created.') }
format.xml { render :xml => #fb_model, :status => :created, :location => #fb_model }
end
else
respond_to do |format|
format.html { render :action => "new" }
format.xml { render :xml => #fb_model.errors, :status => :unprocessable_entity }
end
end
end
When I create a record, my logs show:
Koala::Facebook::APIError (HTTP 500: Response body: {"error":{"type":"Exception","message":"Could not retrieve data from URL."}}):
If I edit the controller to use a static url for testing, everything works fine.
...
if #fb_model.save
Koala::Facebook::API.new(app_token).put_connections( current_user.fb_uid, "namespace:action", :object => "http://myapp.com/fb_model/2" )
...
Why can't I pass the record's url to FB from within the create controller using fb_model_url(#fb_model)?
I eventually got to the bottom of this. It's actually a really frustrating issue, as there is no indication that this is the problem in any logs or elsewhere.
The problem was that I was deploying/ testing on Heroku, and only had 1 web dyno running. My app was unable to handle both the Facebook request and the post/ get simultaneously, causing the error.
This has been addressed in another question Facebook Open Graph from Rails Heroku. It's really not what I was expecting, and I didn't come across this question in any of my earlier searching. Hopefully this can help someone else.
I solved the issue by switching from thin to unicorn.
build is finalised when the parent model is saved, and you dont seem to be operating on a parent.
I think you actually want this:
#fb_model = current_user.fb_models.new(params[:fb_model])
Also you seem to be calling #fb_model.save twice which is wrong.
Thanks for posting your findings - I've been dealing with this issue for the past couple of days and wouldnt have figured that. So when you simply increased your dyno load, you no longer had this error? I was on the verge of just using the Javascript SDK even though my 'put_connections' callbacks work in the heroku console.

ActionView::TemplateError (Missing template) In ruby on rails

I am running a RoR application (rails 2.3.8, ruby 1.8.7), the application runs fine on my local machine. but on production the logs show the following error:
ActionView::TemplateError (Missing template folder/_file_name.erb in view path app/views) on line #19 of app/views/layouts/main.rhtml:
19: <%= render :partial => "folder/file_name" -%>
the file name exists as folder/_file_name.html.erb, I tried to reproduce the problem on the production environment but didnt have any luck, for some reason rails application asks for folder/_file_name.erb at some times while other times it searches for the right file folder/_file_name.html.erb.
Could someone explain to me what is going on?
The same also occurs for .rhtml files, rails application requests .erb at times while others get the right .rhtml file
update:
<%= render :partial => "shared/meta_tags" -%>
<%= render :partial => "shared/common_resources" -%>
<%= render :partial => 'shared/ads/oas' -%>
Any pointers on this issue will be helpful,
thanks in advance
Whats the format of the request?, for the first template (folder/_file_name.html.erb) it will only be correct if the request format is html, but not if it is ajax or any other custom type you have in your app. One quick soluction would be to rename it to folder/_file_name.erb if you want to use the same partial for all the formats
Is there a controller action with the same name as that file?
If you have a foo controller with a bar action and no response defined in your action, Rails will try and render views/foo/bar.html.erb.
If that's not what you want, you need to define a response in your controller and tell Rails to render the appropriate partial, like so:
respond_to do |format|
format.html do
render :partial => "/foo/bar"
end
end
In the latter case, Rails will render "views/foo/_bar.html.erb"
In some cases You can't prevent this error as there are load reasons like missing cache, unknown request format and etc
You can try to restrict the number of predefined formats like:
get '/about-us' => 'controller#about', :format => /(?:|html|json)/
However, I added the following method in my application_controller.rb file so that such errors will render a 404 page rather failing with a error message on screen
rescue_from ActionView::MissingTemplate, :with => :rescue_not_found
protected
def rescue_not_found
Rails.logger.warn "Redirect to 404, Error: ActionView::MissingTemplate"
redirect_to '/404' #or your 404 page
end
you can wrap this code in a if statement, something like this if Rails.env.production? given that the env is setup so your dev environment wont be affected

Simplest way to define a route that returns a 404

I've got a requirement to specify a named route in a Ruby on Rails project that returns the public/404.html page along with the 404 server response code.
Leaving it blank is not an option, please don't question why, it just is :) It absolutely must be a named route, or a map.connect entry would do.
Something like this would be great:
map.my_named_route '/some/route/', :response => '404'
Anyone have any idea what's the easiest way to do something like this. I could create a controller method which renders the 404.html file but thought there might be an existing cleaner way to do this. Looking forward to any responses - thanks,
Eliot
You can route to a rack endpoint (rails 3) that vends a simple 404:
match 'my/route', to: proc { [404, {}, ['']] }
This is particularly handy, for example, to define a named route to your omniauth endpoint:
match 'auth/:action', to: proc { [404, {}, ['']] }, as: :omniauth_authorize
In your routes.rb:
map.my_404 '/ohnoes', :controller => 'foobar', :action => 'ohnoes'
In FoobarController:
def ohnoes
render :text => "Not found", :status => 404
end
If you need to render the same 404 file as a normal 404, you can do that with render :file.
See ActionController::Base documentation for examples.
Why dont you do this in Apache/nginx where you use mod_rewrite (or however nginx does rewrites) to link to a non-existent page or instead send a 410 (Gone, no longer exists) Flag?
Anyway, if you want the rails app to do this, I think the way is as you suggested, create a named route to an action that does a render(:file => "#{RAILS_ROOT}/public/404.html", :status => 404)
Slighly shorter version than the previous answers to 404 any get in one line.
get '*_', to: ->(_) { [404, {}, ['']] }

Resources