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.
Written by joris
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#