Search code examples
ruby-on-railsparametersgenerator

How to set default parameters in the index_helper method for rails generators?


I use the index helper like this

= link_to <%= index_helper(type: :url) %>

I want to pass default params so the generator creates resource_index_path(my_params). I looked at the method definition but couldn't see how to make this work. Is it even possible without overrides?


Solution

  • # File railties/lib/rails/generators/named_base.rb, line 97
    def index_helper # :doc:
      uncountable? ? "#{plural_route_name}_index" : plural_route_name
    end
    

    The method isn't doing anything with any variables passed to it.

    But, as you'll note, it's just returning a string, so you can freely append to it as you please:

    = link_to <%= "#{index_helper}?name=Bob&age=32&is_admin=true" %>
    

    But I'm not sure why you're not just creating a standard path or URL helper:

    # edit path:
    = link_to <%= send("edit_#{resource_name}_path", all: "the", params: "you could want") %>
    
    # index path:
    = link_to <%= send("#{resource_name}_path", all: "the", params: "you could want") %>
    
    # show path:
    = link_to <%= send("#{resource_name}_path", all: "the", params: "you could want") %>
    
    # new path:
    = link_to <%= send("new_#{resource_name}_path", all: "the", params: "you could want") %>