Rails InheritedResources - respond_with JSON, using `find_and_return_for_some_grid` instead of `find(:all)`?
I have a model, say User
. I want to call /users
(users_controller#index
) and pass it basically a scope so it returns data based on:
- The format (js, json, html)
- The chart/grid/layout it will be rendered in (highcharts, basic html table, jquery flexigrid, etc.)
With inherited_resources
and has_scope
, you can do something like that but it's not quite it.
I want to return [{:page => 10, :cells => [{:name => "User A"}...]}]
if params are something like {:action => "index", :format => "js", :grid => "flexigrid"}
, and return [#<User name='User A'>...]
rendered in a haml template if it's just html.
How do I do that RESTfully in Rails wit开发者_Python百科h inherited resources?
Something like this:
class UsersController < InheritedResources::Base
respond_with :js, :method => :find_and_return_for_grid
end
Does this require me creating my own Responder?
You need to override the index method, something like:
def index
index! do |format|
format.html
format.js do
if(params[:grid] == "flexigrid")
render :json => format_for_grid(collection).to_json
end
end
end
end
With format_for_grid a method that convert an array of Users to the data format you want
Personaly speaking I won't format the js response like this, I mean splitting the response in cells is something I would do on view side with js, beacause has to do with the way you want to display the data, I think it would taste more Restful to just return the non display-oriented collection.to_json
精彩评论