Rails 3路由约束问题

时间:2011-06-11 03:40:27

标签: ruby-on-rails-3 routes constraints

我正试图让它成为这样的网址:

/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"}

1 个答案:

答案 0 :(得分: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。