Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

rails link_to_if controller, action and format exist

Rails • Asked by Jay Killeen

I am trying to dynamically render some links to the index action on a range of controllers.

Essentially just create a table of all my models with a count of their records and a link_to the index page as html.

How would I link_to_if the controller, action and format combination exist? I have currently tried the below but because the route is the same but with different formats (csv/json). html doesn't exist so the link_to_if should fail and just render the model name.

resources_path  GET     /resourcess(.:format)    resourcess#index {:format=>/(csv|json)/}
<%= link_to_if, controller:, action: 'index' if Rails.application.routes.url_helpers.method_defined?( + '_path') %>
<% Dir[Rails.root.join('app/models/*.rb').to_s].each do |filename| %>
  <% klass = File.basename(filename, '.rb').camelize.constantize %>
  <% next unless klass.ancestors.include?(ActiveRecord::Base) %>
  <% next if klass.abstract_class? %>
    <% next if configuration_tables.exclude? %>
      <td><%= link_to_if, controller:, action: 'index' if Rails.application.routes.url_helpers.method_defined?( + '_path') %></td>
      <td><%= klass.count.to_s %></td>
<% end %>

It looks like the problem is that the parameters being passed into link_to_if aren't quite right.

The documentation for the function at shows this as the signature for the method:
link_to_if(condition, name, options = {}, html_options = {}, &block)

The first parameter you pass will be evaluated down to true/false, which determine whether or not a link is rendered (true), or just text (false). After that you can pass in the text to display ( and the URL options (controller, action, etc).

Hope that helps!

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 31,152+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.