Rails 3 Problem with Routes Constraint

前端 未结 1 886
感动是毒
感动是毒 2021-01-21 16:53

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

相关标签:
1条回答
  • 2021-01-21 16:58

    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.

    0 讨论(0)
提交回复
热议问题