Home Ruby on rails - how to join 4 tables?
Reply: 1

Ruby on rails - how to join 4 tables?

Guilherme H.
1#
Guilherme H. Published in 2018-02-12 02:36:08Z

This is what I have:

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

class User < ApplicationRecord
  has_one :user_score
  has_many :memberships
  has_and_belongs_to_many :groups, through: :memberships # an user can be owner or member of a group
end

class Group < ApplicationRecord
  has_many :memberships
  has_many :members, through: :memberships, source: :user
end

class UserScore < ApplicationRecord
  belongs_to :user
end

What I'm trying to do is to get a list of users from a group ordered by 'total_score' (which is an attribute of UserScore) but I've failing so far.

kiltot
2#
kiltot Reply to 2018-02-12 02:51:02Z

Obviously, I do not have the schema loaded on my machine. So, my answer will be something like

User.joins(:user_score, :groups).where(groups: {name: 'Name of your group'}).order('user_scores.total_score')
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.321485 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO