Forum: Ruby on Rails Trying the ol' articles route, need some help

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
yaphi (Guest)
on 2009-02-15 03:32
(Received via mailing list)
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?)

<code>
// 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
</code>

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.
Maurício L. (Guest)
on 2009-02-15 18:18
(Received via mailing list)
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
-> http://github.com/technoweenie/permalink_fu/tree/master

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)
yaphi (Guest)
on 2009-02-15 21:33
(Received via mailing list)
Thank you very much Maurício!

I'll give that a shot.

On Feb 15, 11:17 am, Maurício Linhares <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.