2011-06-11 53 views
2

我试图让这个我可以有一个网址,像这样:Rails 3中问题的路线约束

/events 
/events/sunday # => The day is optional 

然而,它似乎并没有被连工作虽然我知道它是越来越调用。它位于我的路线文件的底部。

match '/:post(/:day_filter)' => 'posts#index', :as => post_day_filter, :constraints => DayFilter.new 


class DayFilter 

    def initialize 
     @days = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday] 
    end 

    def matches?(request) 
     return @days.include?(request.params[:day_filter]) if request.params[:day_filter] 
     true 
    end 

end 

这里是我的耙路输出:

post_day_filter  /:post(/:day_filter)(.:format)   {:controller=>"posts", :action=>"index"} 
+0

“似乎没有工作”有点模糊。小心解释一下吗?共享'rake routes'的输出对路由相关的问题总是有帮助的。 ;) – coreyward 2011-06-11 03:42:32

+0

我贴了它,但我认为它不会太有帮助。它已经在我的路由文件的底部,并且我已经将调试器放入了我的约束对象中,以确保它被调用,并且它是。它甚至似乎正在返回正确的值。 – Dex 2011-06-11 03:48:33

+0

什么是/意外发生?我假设你对“/ events/sunday”的请求正在返回404s,但这只是一个猜测。 – coreyward 2011-06-11 03:51:09

回答

5

我不知道是什么问题,具体而言,但下面是做同样的事情的更多性能友好的方式:

class ValidDayOfWeek 
    VALID_DAYS = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday] 
    def self.matches?(request) 
    VALID_DAYS.include? request.params[:day_of_week] 
    end 
end 

get ':/post_type(/:day_of_week)' => 'posts#index', :constraints => ValidDayOfWeek 

最大的不同是,这避免了在每次请求初始化一个新ValidDayOfWeek对象。 Rails指南给出了一个示例,您可以在可能每次都需要一个新对象(实时黑名单更新),但它对您的情况具有误导性。

此外,您的matches?方法中有点冗长 - 无需显式返回或条件,因为includes?将按原样返回true或false。

+0

良好的性能提示,我没有意识到'初始化'。你也在'(:/ day_of_week)'上输错了' – Dex 2011-06-11 04:00:56

+0

你是对的。固定! – coreyward 2011-06-11 04:03:02

+0

要记住的一件事是day_of_week是可选的。所以你重写它的方式是行不通的,因为零值是完全没问题的。 – Dex 2011-06-11 04:38:03