Trying the ol' articles route, need some help

Hey there,

I am trying to figure out routing and thought that this would probably
be the best way to learn how to do some complicated routes. I’ve
looked at a lot of people’s methods for getting the /articles/
2009/02/12/some-title to work but they all seem to forget to post some
custom method they’re writing like by_date.

So here was my stab at it, I know I need to gsub the title. I just
don’t know where (in the conditions?)

// routes.rb map.article_page 'articles/:year/:month/:title', :controller => 'articles', :action => "show", :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/ }

// articles_controller.rb
def show
@article = Article.find_by_date(params)

// article.rb
def self.find_by_date(params)
find(:first, :conditions => [“publish_date.year = ? and
publish_date.month = ? and title = ?”, params[:year], params[:month],
params[:title]])
end

I know publish_date.year is wrong but I can’t figure out a way to pull
the year out of the publish_date column here.

Any help would be surely appreciated.

Thank you very much Maurício!

I’ll give that a shot.

On Feb 15, 11:17 am, Maurício Linhares [email protected]

Hi Yaphi,

First, you shoudn’t “gsub” the title, you must transform it into a
“permalink”. A simple way to do this is to use the permalink_fu plugin
GitHub - technoweenie/permalink_fu: ActiveRecord plugin for automatically converting fields to permalinks.

Having it installed, here’s how your model could look like:

class Article < ActiveRecord::Base

#you’ll need a “title_permalink” column at your “posts” table to
hold the permalink value
#this method creates a permalink base on the :year, :month and
:title properties
has_permalink [:year, :month, :title], :title_permalink

def year
publish_date.year if publish_date
end

def month
publish_date.month if publish_date
end

class << self
# this method finds the record with the specified permalink, you
can even pass the params hash directly
def find_by_permalink( options )
first( :conditions => { :title_permalink =>
“#{options[:year]}-#{options[:month]}-#{options[:title]}” } ) ||
raise( ActiveRecord::RecordNotFound, options.inspect )
end

end

end

#at your controller
def show
@post = Article.find_by_permalink( options )
end

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)