Rails get controller action url - ruby-on-rails

I have an action, and I've defined it in the routes.rb
resources :statistics, only: [] do
get 'group_report/:id', to: 'statistics#group_report', as: 'group_report'
end
Then in the method in the model, I want to return the full URL.
Thus, I wrote this method
root_url + group_report_statistics_path(id)
The result is "http://localhost:3000//statistics/group_report/DHo6qzUzYXw"
I thought it was a dirty way, and I need to handle the double slash as well.
Does Rails provide some useful method which I can get the full URL of the action directly?

Rails provides path as well as url helpers for all the routes.
So if you use group_report_statistics_url(id), you will get the full URL.
See Path and URL Helpers on the Rails guides for detailed description.

try this
File.join(root_url + group_report_statistics_path(id))
or
group_report_statistics_url(id)

Related

How to display an action when specifying controller url

I was wondering how to display an action when specifying a controller url. For example; say I have DemoController.rb, and views/demo/index.html.erb file. Also I've specified the route in routes.rb
get 'demo/index'
How can I setup the project so that when I type "localhost:3000/demo" it renders the same layout as "localhost:3000/demo/index"?
Currently when I type in "localhost:3000/demo" I get a "no route matches" error.
You need a get 'demo' => 'demo#index' instead for that URL to work.
That said, you might want to use Rails conventions and maybe pluralize the controller and use RESTful routes instead:
resources :demos, only: :index

Get current path name in Rails

I would like to be able to get the name of the current route in a request in Ruby on Rails. I've found ways I can access the controller and action of the request, but I would like to access a string or symbol of the name.
For example, if I have a users resource;
If I go to /users/1 I would like to be able to get users_path
If I go to /users/1/edit I would like to be able to get edit_users_path
I simply want to retrieve the name of the current route on a given request.
The following code will give it to you.
Rails.application.routes.recognize_path(request.request_uri)
Note that there are a couple of exceptions that can get thrown in ActionDispatch::Routing::RouteSet (which is what is returned from Rails.application.routes) so be careful about those. You can find the implementation of the method here.
You can use the following methods to get the current url in your action but none of them will give you the name of the route like users_path
request.original_url # => www.mysite.com/users/1
request.request_uri # = > /users/1
I had to use request.original_fullpath (Rails 5.2)
You can use the current_page? method to achieve this.
current_page?(user_path(#user))
current_page?(edit_user_path(#user))
Here's a link:
current_page? method

Cant create a link to named routes

I want to create a link to a named route
My routes.db have the following rule
match '/tablero', to: 'tablero#index',via: 'get' , as: 'tablero_main'
I can see the route using rake routes
tablero_main GET /tablero(.:format) tablero#index
But when i use the link_to as follows i get the "undefined local variable or method `tablero_main'" error.
<%= link_to "Tablero",tablero_main %>
Is there anything else i am missing?
You need to append path to the method name, like so:
<%= link_to "Tablero", tablero_main_path %>
Routes
To help you further, you'll need to also consider the role of resources in your routes
As Rails uses a resourceful routing infrastructure, every route you create should be based around a resource. In your case:
#config/routes.rb
resources :tablero, only: :index #-> domain.com/tablero
Admittedly, this will give you the path tablero_index_path, rather than tablero_main_path, but it ensures your routes are not only DRY, but also extensible. Nothing worse than having 100's of "match routes in a route file.
--
Helpers
After that, remember to use the correct route_path helper:
Each "route" path is basically just a helper method (which builds a URL for you). When using link_to, you need to reference the path helper directly. You didn't do this, which lead Rails to come back with the undefined method error

How to display a friendly name in URL in rails

This is my new resource in routes file :
resources :staticpage do
collection do
get :aboutus
get :snacks
get :contactus
end
end
this generates my urls localhost:3000/staticpage/aboutus localhost:3000/staticpage/snacks/ localhost:3000/staticpage/contactus
Instead of this complex url i want to have localhost:3000/aboutus , localhost:3000/snacks/ localhost:3000/contactus in the URL.
using gem can change my action name, but i want to alter "controllername/action" to a simple string.
What modification should be done in the routes path declaration ?
You can simply write matchers for each route like this:
get 'aboutus', to: 'staticpage#aboutus'
get 'snacks', to: 'staticpage#snacks'
get 'contactus', to: 'staticpage#contactus'
Note that you don't need the resources or collection block if you do this.
As per the routes documentation, you will need to define the routes manually (like David Underwood's answer). However, there is an even better way to do it:
#config/routes.rb
static = %w(aboutus snacks contactus)
static.each do |page|
get page.to_sym, to: "staticpage#show", page: page
end
#app/controllers/staticpages_controller.rb
def show
page = params[:page]
render "staticpages#{page}"
end

Accessing URL helpers in routes.rb

I would like to redirect a path in routes using the following lines:
get 'privacy_policy', :controller => :pages, :as => 'privacy_policy'
get 'privacypolicy.php' => redirect(privacy_policy_url)
So that /privacypolicy.php gets redirected to the correct page defined right above it.
However, it's throwing the following error:
undefined local variable or method `privacy_policy_url'
So I'm guessing one cannot use URL helpers in routes.rb. Is there a way to use URL helpers in the route file, and is it advisable to do so?
I know I'm a little late here, but this question is one of the top hits when googling "use url_helpers in routes.rb", and I initially found it when I had stumbled upon this problem, so I'd like to share my solution.
As #martinjlowm mentioned in his answer, one cannot use URL helpers when drawing new routes. However, there is one way to define a redirecting route rule using URL helpers. The thing is, ActionDispatch::Routing::Redirection#redirect can take a block (or a #call-able), which is later (when the user hits the route) invoked with two parameters, params and request, to return a new route, a string. And because the routes are properly drawn at that moment, it is completely valid to call URL helpers inside the block!
get 'privacypolicy.php', to: redirect { |_params, _request|
Rails.application.routes.url_helpers.privacy_policy_path
}
Furthermore, we can employ Ruby metaprogramming facilities to add some sugar:
class UrlHelpersRedirector
def self.method_missing(method, *args, **kwargs) # rubocop:disable Style/MethodMissing
new(method, args, kwargs)
end
def initialize(url_helper, args, kwargs)
#url_helper = url_helper
#args = args
#kwargs = kwargs
end
def call(_params, _request)
url_helpers.public_send(#url_helper, *#args, **#kwargs)
end
private
def url_helpers
Rails.application.routes.url_helpers
end
end
# ...
Rails.application.routes.draw do
get 'privacypolicy.php', to: redirect(UrlHelperRedirector.privacy_policy_path)
end
URL Helpers are created from the routes. Therefore they won't be usable when drawing new routes.
You will have to use gayavat's approach.
-- or --
Redirect using the exact URL like http://guides.rubyonrails.org/routing.html does.
edit:
If it's more than just the one '...php' route, you might want to consider making a redirect controller. Take a look here, how to se it up: http://palexander.posterous.com/provide-valid-301-redirects-using-rails-route
Inside your routes file, you should add this at the bottom, so it doesn't interfere with other routes:
get '/:url' => 'redirect#index'
Something like:
get 'privacypolicy.php' => "privacy_policy#show"

Resources