jonasulveseth
jonasulveseth

Reputation: 47

Rails rest call for several actions

I have a lot of resources in my project. Now i want to implement a "daterange" function for all my resources.

example:

/url/posts/daterange/datefrom-dateto/

/url/schedule/daterange/datefrom-dateto/

I could write a action in each controller where I want to use it but that feels like repeating myself.

How would you implement a global action that can be used by all actions like that?

Is routing the best way or should I write something in application_controller

Upvotes: 0

Views: 101

Answers (2)

shivashankar
shivashankar

Reputation: 1177

I guess you are expecting this for index action alone. For this you can use the following in config/routes.rb

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

If you want it for other actions, you can achieve the same in configuring in routes.rb

Upvotes: 1

Christoph Petschnig
Christoph Petschnig

Reputation: 4157

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.

Upvotes: 1

Related Questions