views:

136

answers:

2

I have the route

map.member 'members/:id/:name_url', :controller => 'members', :action => 'show', :requirements => { :id => /\d+/ }

and on my Member model I have a name_url method which takes the name and converts it to lowercase and changes spaces to dashes

the problem is that if I run

link_to "Bill", member

it gives me an "member_url failed to generate from" error

is there a way to achieve that? I was thinking a view helper that generated the link, but I couldn't access that from the controller if I needed to...

A: 

Assuming this is the show action of the MembersController

class MembersController

  def show
    @member = Member.find_by_name("Bill")
  end

In app/views/members/show.html.erb, You'll want to use:

<%= link_to @member.name, member_path(@member, :name_url => "something") %>
Dan McNevin
yes, that will work too, I was more curious if there was still a way to keep the short syntax of: link_to 'Bill', member
Christopher
If brevity is the concern, maybe creating a helper function is the way to go?in the view:<%= member_link @member %>in the helper file:def member_link(member) link_to member.name, member_path(member, :name_url => member.name_url)end
Dan McNevin
A: 

The problem is the :name_url parameter in your route:

map.member 'members/:id/:name_url', :controller => 'members', :action => 'show', :requirements => { :id => /\d+/ }

When you pass an ActiveRecord object as an option for url_for (which is what link_to does), Rails will implicitly call the model's to_param method. Which unless overridden only returns id the id. You could override to_param, but that won't give you the url you want. Because to_param is used to create the string that replaces id in urls. The best you could do with minimum changes is settle for something like this:

members/:id

where :id is actually :id-:name_url

Really the best option is what Dan McNevin suggests. However if that's too long for you, you can always just make it a helper:

def link_to_member member
  link_to member.name, member_url(member, :name_url => member.name)
end

And use it in place of link_to.

link_to "Bill", member => link_to_member member

EmFi
I will add it to the application helper then, the only trouble is that I can't access that helper from the controller... or can I?
Christopher
You can include the helpers in the controllers you need them. However, you shouldn't be using link_to in a controller.
EmFi
I won't, I was just trying to get the path
Christopher