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
这是我的 rake 路线输出:
post_day_filter /:post(/:day_filter)(.:format) {:controller=>"posts", :action=>"index"}
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
Here is my rake routes output:
post_day_filter /:post(/:day_filter)(.:format) {:controller=>"posts", :action=>"index"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定问题是什么,具体来说,但以下是执行相同操作的更加性能友好的方法:
最大的区别是,这避免了在每个请求上初始化新的 ValidDayOfWeek 对象。 Rails 指南给出了一个示例,您可能每次都想要一个新的对象(实时黑名单更新),但对于像您这样的情况来说它会产生误导。
另外,您的
matches?
方法有点冗长 - 不需要显式返回或条件,因为includes?
将按原样返回 true 或 false。I'm not sure what the problem is, specifically, but the following is a much more performance-friendly way of doing the same thing:
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.
Also, you were getting a bit verbose in your
matches?
method — no need for explicit returns or a conditional, asincludes?
will return either true or false as is.