Last Updated: February 25, 2016
·
2.714K
· jorism

Rails 4 Scopes and as_json response

I have been working on a Rails API (my first Rails Project).

I wanted to set up a namespace (similar to having namespaces for controllers) for my models. Why? Because I had a as_json method as follows:

def as_json(options={})
    super(options.merge({:include=> {:attachments => {}, :rounds=> {}}}))
end

Depending on who made the request (i.e. /user/position/ vs /organisation/position/) I needed a slightly different JSON response

I finally stumbled over Scopes.

I ended up overriding the as_json method in two different ways.

scope :user, -> {
    def as_json(options={})
        super(options.merge({:include=> {:attachments=> {}, :rounds=> {}}}))
    end
}

vs

scope :organisation, -> {
    def as_json(options={})
        super(options.merge({:include=> {:applications=> {}}}))
    end
}

Now I can either Position.user.all or Position.organisation.all depending on what json response I want.

Source: This is a well written blog post where I got inspired.

Active Record scopes vs class methods

3 Responses
Add your response

Just FYI - if you are building just API, take a look at rails-api

over 1 year ago ·

I am using rails-api:)

over 1 year ago ·

great. without digging into it i always wondered how to achieve this. thanks.

might come in handy for my plans for Starve ;)

over 1 year ago ·