Вопрос

I'm trying to get the path in Rails to a model that I don't necessarily know the class of in a rake task (so it's not in an .erb).

I know that I can do this:

Rails.application.routes.url_helpers.<model>_path(model)

But what if I don't necessarily know the model? It seems not Rails-y to switch on the model.class or any other such inspection. I'm just looking for the default path or url to the model.

Edit: To clarify what I mean by default path, it's the href you get when you do link_to; i.e., you can do this:

<%= link_to "my model", @model %>

without specifying a url helper like model_path. That's what I'm looking for.

Это было полезно?

Решение

Internally, link_to calls url_for to get the path for the given arguments.

If you call url_for with a model, it'll forward further to polymorphic_path or polymorphic_url.

So something like this should work, if you just want the path

task :some_task => :environment do
  include Rails.application.routes.url_helpers

  # ...

  path  = polymorphic_path(some_model_instance) # => e.g. "/widgets/42"
end

You can also just use url_for, but you'll have to define the :host option. See here for more

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top