Ask A Question


You’re not receiving notifications from this thread.

rails link_to_if controller, action and format exist

Jay Killeen asked in Rails

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!

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 79,047+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.