Topic: variable variables in restful path helper methods?

Hello, I have a sort of a problem here,
I have two links here:

<td class="center"><%= link_to 'Edit', edit_income_path(income) %> <%= link_to 'Delete', income_path(income), :method => 'delete', :confirm => 'Really delete?' %></td>

And I use it in seven templates (every template is a little different so I can't make one partial), is there a way I can move those links into an application helper? I tried something like this:
  def edit_link(resource)
    link_to 'Edit', edit_resource_path(resource)
    # how do I make the path read the resource variable? :<
    # link_to 'Edit', edit_(resource_name?)_path(resource)
  end

  def delete_link(resource)
    link_to 'Del', resource_path(resource), :method => 'delete', :confirm => 'Really delete?'
  end


but the resource would be the instance from the template:
<td class="center"><%= edit_link income %> <%= delete_link income %></td>

I'm not even sure if it can work this way. In PHP you can use $$resource.
Thanks, Ollie.

Last edited by Ollie (2009-01-30 07:56:37)

Re: variable variables in restful path helper methods?

  def edit_link(resource)
    link_to 'Edit', eval("edit_#{resource.class.name.underscore}_path(resource)")
    #resource.class => SomeModel
    # .name => "SomeModel"
    # .underscore => "some_model"
    # if you needed the plural version, you'd use .tableize instead of .underscore
    # methods of ActiveSupport::Inflector, see API for details
  end

  def delete_link(resource)
    link_to 'Del', resource, :method => 'delete', :confirm => 'Really delete?'
    # no tricks required here, rails guesses the right "/resources/id" directly from the resource object passed (kind of like we did above with edit), and the :method => "delete" does the rest.
  end

Re: variable variables in restful path helper methods?

Awesome, thanks a bunch!

Re: variable variables in restful path helper methods?

Use polymorphic_path. Example:

edit_polymorphic_path( resource )

If I've helped you out with something, feel free to recommend me on working with rails.

Re: variable variables in restful path helper methods?

lol. that somehow escaped my attention until now. Kinda embarassing.

Thanks!

Re: variable variables in restful path helper methods?

Duplex wrote:

lol. that somehow escaped my attention until now. Kinda embarassing.

Thanks!

Lol. Yeah, I thought it was a bit weird how you were using eval, figured you just didn't know about polymorphic_path, even then I probably would have used send personally - I like to avoid eval if I can help it.

If I've helped you out with something, feel free to recommend me on working with rails.