0

How can I do a link_to that I can modify like the object class string?

First off, I have my objects as polymorphic (book, magazine) so I need to user link_to(@object.title, [@object.user, @object]). This make's it polymorphic like user_book_path or user_magazine_path as expected.

My question is how can I change the user part to writer eg. writer_magazine_path or writer_book_path? Cause in my routes I have named user as writer and I'm wondering how I can do it to the link_to method.

note Don't know if I titled it correctly. Correct it if so.

index
  • 3,697
  • 7
  • 36
  • 55

2 Answers2

0

Try this, Make helper for example

In your Helper

def *method_name(@object)*
  link_to "whatever" write_"#{object}"_path
end

Now, In your view file

<%= method_name(@object) %>
Dipak Panchal
  • 5,996
  • 4
  • 32
  • 68
  • Should the link_to be a string or something cause I think you're doing interpolation on the path? – index Dec 28 '12 at 05:01
  • helper it's like a view file whatever you write in view that you can also write in helper so you can use link_to in helper – Dipak Panchal Dec 28 '12 at 05:27
  • I haven't tried it yet but I don't think the "#{object}" would interpolate itself on the write_*_path. But I'll try it out when I get back to my code. – index Dec 28 '12 at 05:38
0

In this case you can make use of eval, as follows

<%= link_to @object.title, 
    eval("writer_#{@object.class.name.downcase)_path(pass_object_here)"} %>
Super Engineer
  • 1,966
  • 1
  • 13
  • 21