Conditional "link_to" helper function - AYUDAME POR FAVOR

Hello,

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.    3. def link_to_if_owned(owner_id, anchor_text, where_to_go)    4. if current_user.id == owner_id # current user is owner    5. "#{link_to anchor_text, where_to_go}"    6. else    7. anchor    8. end    9. 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 => @car.id")%>

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

   1. <a href=":controller => :cars, :action => :add_gas, :car_id => @car.id">Add Gas</a>

How can I make it so the link works?

Hello,

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.   3. def link_to_if_owned(owner_id, anchor_text, where_to_go)   4. if current_user.id == owner_id # current user is owner   5. "#{link_to anchor_text, where_to_go}"

That's unnecessary: just link_to ... is enough

  6. else   7. anchor   8. end   9. 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 => @car.id")%>

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

Fred

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 => @car.id")%>

But also like this:

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

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 => @car.id")%>

But also like this:

<%= 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 => @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
it.

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

Fred

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

Thanks again for the advice.