Ask A Question

Notifications

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 klass.name, controller: klass.name.pluralize.underscore, action: 'index' if Rails.application.routes.url_helpers.method_defined?(klass.name.pluralize.underscore + '_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? klass.name %>
    <tr>
      <td><%= link_to_if klass.name, controller: klass.name.pluralize.underscore, action: 'index' if Rails.application.routes.url_helpers.method_defined?(klass.name.pluralize.underscore + '_path') %></td>
      <td><%= klass.count.to_s %></td>
  </tr>
<% end %>
Reply

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 api.rubyonrails.org 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 (klass.name) and the URL options (controller, action, etc).

Hope that helps!

Reply
Join the discussion
Create an account Log in

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

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

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