Get current path name in Rails - ruby-on-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

Related

Rails get controller action url

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)

Rails - How To Get Full URL in Model

In my Rails 5 app, I'm trying to get the full URL for my instance, but when I tried to use url_for as suggested in this SO question, I get an error, NoMethodError: undefined method 'url_for' for #<Product:0x8646fc0>.
Full URL with url_for in Rails
def get_url
url = url_for(self)
end
I also tried product_url(self) and received a similar error.
What's the proper way to get the URL for my instance? Thanks!
helper method is only available in view or decorator.
it's better to define url in the decorator.
if you want to use helper method in the model, try this
def url
Rails.application.routes.url_helpers.product_url(self)
end

Manage manualy Rails router for SOE and multilingual

I'm a beginner with Rails, and I ready all this very usefull tutoriel (French) But I have some other question..
I learn how the basic Rails router works (based from Controller name) :
RequĂȘte HTTP URL Action
-----------------------------------
GET /users index
GET /users/1 show
GET /users/new new
POST /users create
GET /users/1/edit edit
PUT /users/1 update
DELETE /users/1 destroy
But I want make some modifications :
1/ SOE
I need to update route for user retrieve (show, update, ..) and i want use #user[:username] on URI instead of #user[:id]
So in my case : /users/arthur instead of /users/1
2/ Multilingual
On the same type of problem, i want add one the start of the URI the ISO code for each country (ex : /fr/users/) and create alias on my URI.
For example, before the Rails router was initialized I want update all routes like :
/utilisateurs/... -> /users/...
/produits/... -> /products/...
Can I do it easly ?! And these changes may be applicable by the link_to function ?
So if i'm call like_to #user ( with #user data : {'name'=>'arthur', 'lang'=>'fr'} ) the function should return /fr/utilisateurs/arthur instead of /users/1
Thank you all for helping !
You can use Translated Paths for the multilingual definitions found here. As for the use of username for the param you can follow this, basically you override to_param and that will be used to generate the url when using link_to and other helpers.

how do you determine if request.referrer matches a Rails restful path?

As we know from this post, in Rails, you can get the previous url by calling
request.referrer
But how do you check if the previous url matches one of the restful paths in
your Rails application?
By restful paths, I mean paths provided by Rails, such as,
books_path
book_path(book)
edit_book_path(book)
Of course I can do a regular expression string match on request.referrer, but I think it's a bit ugly.
One particular case, in my application, is that request.referrer can be
"localhost:3000/books?page=4"
and I want to it to match
books_path
which returns "/books"
In this case, how can I check if there's a match without doing regular expression string
match? (if this is at all possible)
Thanks
P.S. I have tried regular expression string match, and it works. I just thought there might be a better way in Rails.
You could extract the path portion of the request.referer using the following:
URI(request.referer).path
You can then use Rails.application.routes.recognize_path to check if path maps to a controller and action, e.g.:
my_path = URI(request.referer).path
# => /books
Rails.application.routes.recognize_path(my_path)
# => {:action=>"show", :controller=>"books", :page=>"4"}
Though not certain of what you want to do with that, pretty sure rails support better ways of controlling redirects. Nevertheless, I guess this is what you are looking for:
request.referer == books_url(page: params[:page])
UPDATED:
This way, even if there's no params[:page]. This would still work properly.
Since recognize_path was deprecated, this is another way of doing it:
Name your route in your routes config using the as keyword:
get 'foo/bar' => 'foo#bar', as: :foo_bar
Then you can do the check like this:
if URI(request.referer).path == foo_bar_path
do_something()
end

Command to use inside the controller's action logic to determine the route that caused that action to be invoked?

I used rake routes to print out all of the routes in my application.
What I found is that a couple of routes map to the same controller/action combination.
So in my action I would like to display which route was actually used to track down where everthing is coming from.
I tried just rendering params.inspect as text:
render :text => params.inspect
But I don't get the route information in the hash.
Is there some other command to reveal the currently used route from within the action?
I think you can use
request.url or params[:action] or params[:controller] depending on what you need.
request.url
This will tell you the route that caused your current action to be invoked.

Resources