joep
1
Hello,
I need to write a function that will return a link only if the current
user is the owner. Here is my code…
- application_helper.rb
-
- def link_to_if_owned(owner_id, anchor_text, where_to_go)
- if current_user.id == owner_id # current user is owner
-
"#{link_to anchor_text, where_to_go}"
- else
-
anchor
- end
- end
And here’s how I call it in the view…
- <%= 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)…
- Add Gas
How can I make it so the link works?
joep
2
On 8 Jul 2008, at 16:51, Joe P. wrote:
-
"#{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).
Fred
joep
3
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”)%>
joep
4
Thanks, yeah, I tested it right after I wrote my comment. Turns out it
works already.
Thanks again for the advice.
joep
5
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 => @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