brain.rbinstance_missing
Linking back in Rails is not complicated, the basic syntax of the link_to helper supports this options pretty easily:
link_to “Back”, :back
HTTP_REFERER.
This is pretty straight forward, but what if the user clicked on this link from an email? or from twitter? then the HTTP_REFERER variable sill be empty.
In order to solve this, i tweaked the link_to helper to check if there’s a value in HTTP_REFERER before creating a link to it, So this link_to_back_or_default helper works exactly like link_to does, but redirects back if there is any value.
Add a method in your application_helper.rb:
def link_to_back_or_default(*args)
name = args.first
options = args1 || {}
html_options = args2 unless @back_url = @controller.request.env[“HTTP_REFERER”] @back_url = self.url_for(options) end if html_options html_options = html_options.stringify_keys href = html_options[‘href’] convert_options_to_javascript!(html_options, url) tag_options = tag_options(html_options) else tag_options = nil end href_attr = “href=\”#{@back_url}\"" unless href “<a #{href_attr}#{tag_options}>#{name || url}”end
Let’s say you have a ProductController in your application.
When you redirect to ProductsContoller#show you want the back link to redirect to the last page if there is any, or point to the ProductsController#index if there isn’t any last page.
That’s all you need to do:
link_to_back_or_default ‘Back’, products_url
simple.
Enjoy!
| Variable | Value |
|---|---|
| GITHUB | |
| WWR | { :working_with_rails => 'http://www.workingwithrails.com/person/5844-elad-meidar' } |
| IRC | { 'irc.freenode.net' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]} |
| SKYPE | eladmeidar |
You're seeing this error because I think it is funny.