Rails 3路由约束的问题 [英] Rails 3 Problem with Routes Constraint
问题描述
我想要这样,我可以有一个像这样的网址:
I'm trying to make it so that I can have a urls like this:
/events
/events/sunday # => The day is optional
但是,它似乎并不工作,即使我知道它正在称为。它位于我的路线文件的底部。
However, it doesn't seem to be working even though I know it is getting called. It is at the bottom of my routes file.
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
这是我的rake路由输出: / p>
Here is my rake routes output:
post_day_filter /:post(/:day_filter)(.:format) {:controller=>"posts", :action=>"index"}
推荐答案
什么问题,具体来说,但以下是一个更性能友好的方式做同样的事情:
I'm not sure what the problem is, specifically, but the following is a much more performance-friendly way of doing the same thing:
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指南提供了一个例子,您可以每次想要一个新对象(实时黑名单更新),但它对您的情况具有误导性。
The biggest difference is that this avoids initializing a new ValidDayOfWeek object on every request. The Rails guide gives an example where you might want a fresh object each time (real-time blacklist updating), but it's misleading for cases like yours.
此外,您的匹配?
方法中有一点冗长 - 不需要显式返回或条件,因为包括? code>将返回true或false。
Also, you were getting a bit verbose in your matches?
method — no need for explicit returns or a conditional, as includes?
will return either true or false as is.
这篇关于Rails 3路由约束的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!