Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make custom _url helper in Rails 3?

I've got this

match '/news/:year/:id' => 'news#show', :as => :news

I want to use:

<%= link_to n.title, n %>

(which returns /news/n.id/current_news.id instead of /news/n.date.year/n.id)

I want to get rid of this:

<%= link_to n.title, news_url(n, :year => n.date.year) %>

How to do that?

like image 858
usrkkkxx Avatar asked Jun 30 '11 02:06

usrkkkxx


2 Answers

You can override the helper that generates the path

adding something like this to the NewsHelper module should do the trick:

def news_path(news)
    "/news/#{news.date.year}/#{news.id}"
end

then <%= link_to n.title, n %> will give you the url you want for news objects

like image 62
mike Avatar answered Nov 05 '22 14:11

mike


You can do something like this in a helper file:

def custom_link_to(*args)
  name         = args[0]
  obj          = args[1]
  if obj.is_a?(News) # or whatever class you are using
    link_to(name, news_url(obj, :year => obj.date.year))
  else
    link_to(args)
  end
end

Then in your view:

<%= custom_link_to n.title, n %>

Or you could override the link_to helper method with some similar code. I would prefer the custom_link_to method because it presents less chance of screwing up other link_to calls. But if you do it right you could certainly get away with it.

like image 42
Midwire Avatar answered Nov 05 '22 12:11

Midwire