Rails 3 Problem with Routes Constraint

2019-02-25 20:49发布

问题:

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

回答1:

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

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, as includes? will return either true or false as is.