Mathieu
Mathieu

Reputation: 4787

Is it possible to point to a helper or a concern method inside a link_to (Rails 4)

Is it possible to replace the standard link_to structure :

link_to "France", :controller => :static_pages, :action => :france

BY referring not to a controller but to a helper's method or a concern's method

 - link_to "France", :helper => :my_helper, :action => :method_name_inside_helper

 - link_to "France", :concern_module => :country_concern_module, :action => :method_name_inside_the_concern_module

Why would I like to do that: Indeed using a controller forces me to create ONE route per country and use redirects...I'd rather just use a helper or a concern module that do do force me to create a route when using one of their method.

Thanks!

Upvotes: 0

Views: 725

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

MVC

The answer to this is that since Rails is built on the MVC programming pattern, you have to adhere to certain "conventions which are present in this type of framework:

enter image description here

The bottom line here is that when you request a URL, what you're really doing is sending a request to Rails, which will then route the request to a particular controller action.

Helpers & concerns are there to provide extra functionality to the various controller actions that you serve.

To answer your question - you need to use your routes to send a request to your controller, which will then be able to pull data from your model, showing in your view

--

OOP

A further explanation of this will come from object-orientated programming, which Rails is very much built on.

Everything you do in Rails needs to revolve around objects. Each controller action, model call, view, link, etc, needs to involve objects. These allow you to create a system which advocates & facilitates the adaptation & manipulation of the various objects

Now, your question is whether you can "route directly to a helper method or concern". The answer here is "no", simply because that is not object orientated. It's method orientated

Ever wonder why Rails' routes are declared with resources? enter image description here

It's because Rails entire system needs to be constructed around objects / resources. This means your controllers will be able to provide a central set of "CRUD" actions to support the manipulation of these objects for you

Upvotes: 2

RAJ
RAJ

Reputation: 9747

Short Ans: No, you can't.

Long Ans:

You can't point links or URLs directly to helper or concerns. These are modules, they can't handle requests.

You will need to point to contoller's action first. In the action, you can call helper/concern methods and return result after processing.

Upvotes: 1

Related Questions