Rails ActiveRecords with own attributes + associated objects' IDs -



Rails ActiveRecords with own attributes + associated objects' IDs -

i have rather simple activerecords associations such (specifically in rails 4):

an organization has many users a user belongs organization

but in terms of activereocord queries, what's optimal way build query homecoming array of organizations each own array of user ids associated itself? basically, i'd homecoming next info structure:

#<activerecord::relation [#<organization id: 1, name: "org name",.... user_ids: [1,2,3]>, <organization id: 2...>]>

... or distill farther in json:

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

where users not part of organizations table attribute constructed on fly activerecord.

thanks in advance.

edit: after trying few things out, came returned result in format looking for. i'm still not sure (nor convinced) if optimal query:

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

alternatively, jbuilder/rabl approach @kien thanh suggested seem reasonable , approachable. considered current best practice nowadays rails-based api development (the app has back-end , front-end pieces de-coupled)?

the thing aware of library solution such jbuilder or rabl watch performance when build json.

as query utilize includes instead of joins pull info back.

orgs = organization.includes(:users)

you should not have grouping results way (unless grouping aggregate value).

activerecord::relation gives automatic helper methods, 1 of association_ids.

so if create own json hash can

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

edit: forgot add together reference has_many http://guides.rubyonrails.org/association_basics.html#has-many-association-reference

activerecord ruby-on-rails-4 model-associations

Comments

Popular posts from this blog

javascript - THREE.js reposition vertices for RingGeometry -

javascript - I need to update the text of a paragraph by inline edit -

assembly - What is the addressing mode for ld, add, and rjmp instructions? -