0

我的项目中有很多资源。现在我想为我的所有资源实现一个“日期范围”功能。

例子:

/url/posts/daterange/datefrom-dateto/

/url/schedule/daterange/datefrom-dateto/

我可以在每个我想使用它的控制器中编写一个动作,但这感觉就像在重复自己。

您将如何实现一个可供所有此类操作使用的全局操作?

路由是最好的方式还是我应该在 application_controller 中写一些东西

4

2 回答 2

1

I would use parameters instead of path segments, like /url/posts?datefrom=2012-12-05&dateto=2012-12-31, because that wouldn't affect the routes and is still RESTful.

Then, I would like to have the following class macro:

class PostsController < ApplicationController
  allows_query_by_daterange
  #...
end

And the mixin:

module QueryByDateRange
  def allows_query_by_daterange
    include QueryByDateRange::Filter
  end

  module Filter
    extend ActiveSupport::Concern
    included do
      before_filter :apply_daterange  # maybe only on the index action?
    end

    def apply_daterange
      # set @datefrom and @dateto from params
    end
  end
end

Make it available to all controllers:

class ApplicationController
  extend QueryByDateRange
end

In your action, you have now at least the instance variables set. This solution could be driven much further, where the condition gets automatically appended to your ARel statement and adding the macro would be all you need to do.

Hopefully, my answer can show you a possible direction where to go.

于 2012-12-06T10:36:29.337 回答
1

我猜你预计这仅用于索引操作。为此,您可以在 config/routes.rb 中使用以下内容

match '/(:controller)/(/daterange/(:datefrom)-(:dateto))(.:format)' => ':controller#index', :via => :get

如果您希望它用于其他操作,您可以在 routes.rb 中进行配置

于 2012-12-06T11:06:10.757 回答