Rails view Helper function and link_to function

I am trying to create a helper function (e.g. in application_helper.rb ) that generates link_to based on the parameters passed to the helper function. If I put the link in an ERB file, this would be in the format:

 <%= link_to 'Some Text', { :controller => 'a_controller', :action => 'an_action' } %> 

In a helper function, text, controller, and action are transmitted or evaluated. Code in helper function:

 params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}" html = "#{link_to some_text, params }<p />" return html 

The generated link has the correct text, however the parameters are literally the contents of the params string.

How can I get the params string to evaluate (as in the ERB file)?

+4
source share
2 answers

I think it’s harder in your head. If you are not trying to do something very strange (and impractical), this will work:

 def link_helper text, controller, action link_to text, :controller => controller, :action => action end 

Although, as you can see, this should not be done as his assistant - it is hardly more simple than the functionality that it wraps, and much less flexible.

The helper link_to returns a string, so it’s very easy to use the way you want:

 def link_helper text # some helper logic: controller = @controller || "pages" action = @action || "index" # create the html string: html = "A link to the #{controller}##{action} action:" html << link_to(text, :controller => controller, :action => action) html # ruby does not require explicit returns end 
+10
source

You can just use url_for helper.

link_to "Some Text", url_for (: action =>: action_name ,: controller =>: controller_name)

0
source

Source: https://habr.com/ru/post/1335235/


All Articles