I am creating a web application that utilizes Rails 3 to serve up JSON. I use AngularJS' ngResource to interact with the RESTful server-side data.
On the rails side, I have two models: Genre and Book.
- Each Genre
has_manyBooks - Each Book
belongs_toa Genre - In
routes.rb, my resources are listed asresources :genres, :books. They are not nested.
As I'm sure you know, this allows me to do things like call Genre.where(name: "sci-fi").first.books that returns me an array.
I'd like to do something like this from the Rails controller and the Angular ngResource factory. It's working properly for me for the standard REST operations...
However, I'm trying to define a custom REST operation where I could call something like this: Genre.books({ id: 1 }) and have it return an array of books that belongs to the Genre with an id of 1.
Here's my genres_controller.rb:
class GenresController < ApplicationController
respond_to :json
...
def books
@genre_books = Genre.where(id: params[:id]).first.books
respond_with @genre_books
end
end
Here's my Angular ngResource for genre (written in coffeescript):
app = angular.module("ATWP")
app.factory "Genre", ($resource) ->
$resource "/genres/:id",
id: "@id"
,
....
books:
method: "GET"
I've tried tacking on isArray: true to the REST operation to no avail. I simply get back the Genre resource itself but not an array of books that belong to the Genre.
So, what am I missing? Is it a bad idea in the first place to do something like what I'm trying to do in the above examples? Any input is appreciated.