views:

34

answers:

2

In my partial template, there is a varible named "resource", it may be a question or an answer.

I want to build a link to edit it, but when I use it, I don't know what it is, so I can't write:

<%=link_to 'edit', edit_question_url(resource)%>

or

<%=link_to 'edit', edit_answer_url(resource)%>

I wonder if there is such a method, say "url_for_edit()", can be used as:

<%=link_to 'edit', url_for_edit(resource)%>

Is there such a method?

A: 

You can create a helper in ApplicationHelper like this:

def edit_question_or_answer_url(resource)
    return edit_question_url(resource) if resource.kind_of? Question
    return edit_answer_url(resource)   if resource.kind_of? Answer
    raise ArgumentError.new "unknown resource: #{resource.class.name}"
end

Or by metaprogramming:

def edit_question_or_answer_url(resource)
  send "edit_#{resource.class.name.underscore.pluralize}_url".to_sym, resource
end

With the first approach the application raises an exception if resource isn't valid. In the second the exception is only raised if resource isn't a resource

I didn't test this code, but I think is 100% correct.

Hope this helps.

pablorc
@pablorc, your answer is OK, but is too complicated. `polymorphic_url` is much simpler. Thanks all the same.
Freewind
+3  A: 

you can try polymorphic_url(resource) prefixed with edit_polymorphic_url(resource) http://api.rubyonrails.org/classes/ActionController/PolymorphicRoutes.html#M000264

or more detailed

http://caboo.se/doc/classes/ActionController/PolymorphicRoutes.html

dombesz
@dombesz, thanks for your answer, it is just what I want
Freewind