开发者

Rails routing model method parameter

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 whic开发者_运维问答h 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...


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") %>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜