Conditional "link_to" helper function - AYUDAME POR FAVOR


I need to write a function that will return a link only if the current
user is the owner. Here is my code…

  1. application_helper.rb
  2. def link_to_if_owned(owner_id, anchor_text, where_to_go)
  3. if == owner_id # current user is owner
  4. "#{link_to anchor_text, where_to_go}"
  5. else
  6. anchor
  7. end
  8. end

And here’s how I call it in the view…

  1. <%= link_to_if_owned(@car.owner_id, “Add Gas”, “:controller =>
    :cars, :action => :add_gas, :car_id =>”)%>

The downside is that the actual HTML rendered is a bad link (this is
what I get)…

  1. Add Gas

How can I make it so the link works?

On 8 Jul 2008, at 16:51, Joe P. wrote:

  1. "#{link_to anchor_text, where_to_go}"

That’s unnecessary: just link_to … is enough

don’t pass the link parameters in a string (after all you wouldn’t
with a ‘normal’ link_to would you).


How can I pass it if I don’t know how many parameters there are going to
be each time? Let’s say I want to use it like this:

<%= link_to_if_owned(@car.owner_id, “Add Gas”, “:controller =>
:cars, :action => :add_gas, :car_id =>”)%>

But also like this:

<%= link_to_if_owned(@car.owner_id, “List Cars”, “:controller =>
:cars, :action => :list”)%>

Thanks, yeah, I tested it right after I wrote my comment. Turns out it
works already.

Thanks again for the advice.

On 8 Jul 2008, at 19:07, Joe P. wrote:

<%= link_to_if_owned(@car.owner_id, “List Cars”, “:controller =>
:cars, :action => :list”)%>

That doesn’t make any difference.
:controller => :cars, :action => :add_gas, :car_id =>

is only one parameter (they’re collected into a single hash. try it).
You don’t need to change your helper at all, just how you are calling

(if you ever need to capture a variable number of arguments, use
*args. You don’t need it here though)


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs