Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing engine routes from Rails.application.routes.url_helpers

I would like to know how to access engine routes by using Rails.application.routes.url_helpers.

I have a factory object that creates a string including a dynamically generated url. Currently, I can generate urls by using Rails.application.routes.url_helpers.(INSERT PATH NAME).

However, it can only access the routes in the main app. I cannot access the routes of engines mounted on the main app.

Things I have tried

  1. I've tried to use Rails.application.routes.engine_name where engine_name is the name under which the engine is mounted on the main app.

  2. I've tried to use MyEngine::Engine.routes.url_helpers to access the routes in the Engine. It works, but I would like to use Rails.application.routes.url_helpers because there are many factory objects like this one, and they are all inheriting from the superclass that delgates url_helper to Rails.application.routes.

Any suggestions? Let me know if any clarification is needed.

like image 608
Sung Cho Avatar asked May 07 '15 23:05

Sung Cho


People also ask

How do I see routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

How do Rails routes work?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

What are Rails resource routes?

Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.


2 Answers

You have to use engine route proxy method. From your example call the url helper using the following syntax as example:

my_engine_engine.articles_path

To rename the proxy method helper, just edit the routes config file inside your rails application:

mount MyEngine::Engine => '/app', :as => 'my_engine'

so you can now call the previous example:

my_engine.articles_path
like image 194
Maroo-b Avatar answered Sep 21 '22 23:09

Maroo-b


Assuming that your engine namespace is EngineName, it should be:

EngineName::Engine.routes.url_helpers.some_engine_path
like image 25
Mat Avatar answered Sep 21 '22 23:09

Mat