我的rails应用程序中有一个博客功能。目前我在该网站上只有4位博客,并且有一种(非常不满意)的方式来这样做:
map.scarlet '/scarlet.:format', :controller => 'blogs', :action => 'show', :id => 'scarlet'
map.alba '/andreasweinas.:format', :controller => 'blogs', :action => 'show', :id => 'alba'
通过输入以下内容可以很方便地访问它们:mysuperwebsite.com/scarlet
现在我想为可访问的博客提供档案:
mysuperwebsite.com/scarlet/2009 - 显示2009年的所有条目
mysuperwebsite.com/scarlet/2009/06 - 显示2009年6月的所有条目
有人会建议如何a)改进我的博客路由,考虑到将来我会有更多的博主,以及b)如何在不破坏路径的情况下路由档案?我在想档案管理员?
型号:
# Blog.rb
class Blog < ActiveRecord::Base
has_many :entries, :dependent => :destroy
belongs_to :user
end
class Entry < ActiveRecord::Base
named_scope :published, :conditions => ["published_at < ?", Time.zone.now], :order => 'published_at DESC'
belongs_to :blog
end
博客控制器:
def show
@blog = Blog.find_by_slug(params[:id])
@entries = @blog.entries.published, :order => 'published_at DESC'
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @blog.entries }
format.rss
end
end
答案 0 :(得分:1)
这是未经测试的,但应该非常接近。不是DRYest解决方案,但您可以重构它。 这将使日期过滤器工作并允许您拥有新博客并支持现有路线。 享受
routes.rb
#(you don't need the .format) bit
# (if you have other routes, like /help, you need to have them before these, since these match /*, /\*/\*, and /\*/\*/\*
map.blogs '/:id/:year/:month', :controller => 'blogs', :action => 'show'
map.blogs '/:id/:year', :controller => 'blogs', :action => 'show'
map.blogs '/:id.:format', :controller => 'blogs', :action => 'show'
博客控制器:
def show
@blog = Blog.find_by_slug(params[:id])
if (params[:year])
if (!params[:month])
date_begin = Date.new(params[:year],1,1)
date_end = Date.new(params[:year],12,31)
date_end = Time.zone.now if date_end < Time.zone.now # to prevent grabbing future posts
@entries = Entries.find(:conditions => [blog => @blog, :published_at => date_begin..date_end ],
:order => 'published_at DESC'
else
date_begin = Date.new(params[:year],params[:month],1)
date_end = date_being.end_of_month
date_end = Time.zone.now if date_end < Time.zone.now # to prevent grabbing future posts
@entries = Entries.find(:conditions => [blog => @blog, :published_at => date_begin..date_end ],
:order => 'published_at DESC'
end
else
@blog.entries.published, :order => 'published_at DESC'
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @entries } # I changed this too
format.rss
end
end