poweratom
poweratom

Reputation: 2434

Rails ActiveRecords with own attributes + associated objects' IDs

I have a rather simple ActiveRecords associations like such (specifically in Rails 4):

But in terms of ActiveReocord queries, what's an optimal way to construct a query to return an array of Organizations each with its own array of user ids associated with itself? Basically, I'd like to return the following data structure:

#<ActiveRecord::Relation [#<Organization id: 1, name: "org name",.... user_ids: [1,2,3]>, <Organization id: 2...>]>

... or to distill it even further in JSON:

[{id: 1, name: 'org name', ... user_ids: [1,2,3]}, {...}]

where users is not part of the Organizations table but simply an attribute constructed on the fly by ActiveRecord.

Thanks in advance.


EDIT: After trying a few things out, I came up with something that returned the result in the format I was looking for. But I'm still not sure (nor convinced) if this is the most optimal query:

Organization.joins(:users).select("organizations.*, '[#{User.joins(:organization).pluck(:id).join(',')}]' as user_ids").group('organizations.id')

Alternatively, the JBuilder/Rabl approach @Kien Thanh suggested seem very reasonable and approachable. Is that considered current best practice nowadays for Rails-based API development (the app has the back-end and front-end pieces completely de-coupled)?

Upvotes: 1

Views: 105

Answers (1)

Kris Robison
Kris Robison

Reputation: 698

The only thing to be aware of with a library solution such as JBuilder or Rabl is to watch the performance when they build the json.

As for your query use includes instead of joins to pull the data back.

orgs = Organization.includes(:users)

You should not have to group your results this way (unless the group was for some aggregate value).

ActiveRecord::Relation gives you some automatic helper methods, one of which is association_ids.

So if you create your own JSON from a hash you can do

orgs.map! {|o| o.attributes.merge(user_ids: o.user_ids).to_json }

EDIT: Forgot to add the reference for has_many http://guides.rubyonrails.org/association_basics.html#has-many-association-reference

Upvotes: 1

Related Questions