dubmojo
dubmojo

Reputation: 6838

Ruby/Rails: How to specify an arbitrary route path via a string in a View, or a route URL in a Model

This bit has been frustrating me all night and I can't find a helped or clean way to do it.

I had a non-ActiveRecord Model (so not stored in the DB) that reflects a dynamic navigation menu, and one attribute of the model's menu items is naturally a route link. (the Model in question essentially has a class with links/routes stored in it, to other Model routes) I don't like the idea of storing URLs, or any navigation data for that matter, in a model, but I can't see a better way to design this.

The link_to attribute could be a route path (e.g. user_path) as a string which would be used in the View to determine the URL. Or, it could be stored in the Model as the URL by retrieving it from the routes via the url_helper. (I think)

So, does anyone have any suggestions on a helper or trick that could solve the problem? url_helper and url_for kind of expect a model with a matching route. In this case the non-ActiveRecord Model is not a normal Model, but a representation of the site's Navigation Menu, linking to other parts of the site.

I really just want a helper or function to say, route_to 'user_path'. Does anyone know if this is possible?

Any help would be appreciated. Thanks!

Upvotes: 0

Views: 498

Answers (1)

dubmojo
dubmojo

Reputation: 6838

The answer, beside the fact I'm probably abusing MVC models, is Rails.application.routes.url_helpers. you can call it with the route path as a direct method and it'll return the url, but the trick that I found is the send method allows calling it with a string representation of the route path. This makes coding for it much easier. Note saying this works as is. It's just an example:

class Something
    attr_accessor :somethings
    def all()
        @somethings = Array.new
        somethings << Something.new('user_root_path')
        somethings << Something.new('edit_user_path')
        somethings << Something.new('edit_pets_path')
    end

    ...

    def initialize(link)
        @link = Rails.application.routes.url_helpers.send link
    end
end

Upvotes: 1

Related Questions