Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-4

Can i use variables in Rails link_to method?


Can i use variable for Rails link_to helper for making different link with variables?

For example, <%= link_to users, users_path %> I have link like this,

And i'd like to change this url with variable examples

So i changed url like this, <%= link_to users, "#{examples}_path" %> This not worked because of whole string change to url.

How can i change my link_to for use this with different variable for DRY codes?


Solution

  • What you're asking is really just how to perform dynamic method calls. In Ruby you can do it with send (and public_send):

    <%= link_to users, send("#{examples}_path") %>
    

    The difference between the two is that send will let you violate encapsulation and call private/protected methods.

    You can also do it by calling call on the Method object:

    <%= link_to users, method("#{examples}_path".to_sym).call %>
    

    However you most likely don't even need this it in the first place. Just use the polymorphic routing helpers to create links from models:

    # a link to show whatever resource happens to be
    <%= link_to resource.name, resource %>
    
    <%= link_to "Edit", edit_polymorphic_url(resource) %>
    <%= link_to "New", new_polymorphic_url(resource_class) %>
    <%= link_to "Frobnobize", polymorphic_url(resource, :frobnobize) %>
    
    # a link to the index 
    <%= link_to resource_class.model_name.plural, resource_class %>
    

    These all use a set of heuristics to figure out what the corresponing path helper is and then call it dynamically with send.

    Or if you want to link to a specific controller or action just use the functionality provided by url_for:

    # link to a specific controller action
    <%= link_to "Baz", { controller: :foo, action: :bar } %>
    
    # Will use the current controller 
    <%= link_to "Baz", { action: :bar } %>