0

Can someone help me in simplifying this line i wrote? other than the ugly syntax, I'm certain there are other methods, other than eval to form a path

return send("link_to", "(#{order_string[:direction]})" 
         ,eval("#{controller}_path(#{query_string})"))

Guranteed that

controller               = contacts
query_string             = 'status: "ASC"'
order_string[:direction] = "ASC"

The above line should result in (and it does)

link_to "ASC",contacts_path(status: "ASC")
4

2 回答 2

2

Being inside a helper method you should be able to do:

return link_to(order_string[:direction], 
               send("#{controller}_path", query_string))

Given your parameters this is equivalent to:

return link_to('ASC', contacts_path(status: 'ASC'))
于 2013-05-09T07:58:27.337 回答
2

To avoid using Eval, I would go with simplifying link_to, and not to use the routes method.

return link_to order_string[:direction],
               controller: controller, query_string

which it will translated to

return link_to 'ASC', controller: "contacts", status: 'ASC'

and in HTML

<a href="/contacts?status=ASC">ASC</a>

Also, beside controller, you can add action and id and Rails is smart enough to do the rest.

于 2013-05-09T08:04:41.680 回答