Group and order, I have a lot of end-to-end model in Rails

Hi i have searched but could not find a way to do this

I have the following models:

class Hierarchy < ActiveRecord::Base
  belongs_to :user
  belongs_to :family
end

      

...

class Family < ActiveRecord::Base
  #attributes rank:integer order:integer
  has_many :hierarchies
  has_many :users, :through => :hierarchies
end

      

...

class User < ActiveRecord::Base
  has_many :hierarchies
  has_many :families, :through => :hierarchies
end

      

Having current_user

, I need to get all the other members of his family, grouped by rank and then ordered by column order.

I would bet what I tried, but it really is not and this request is out of my league. I am using postgres.

+3


source to share


3 answers


I would go with the following approach.

We have to update the user model :)

class User < ActiveRecord::Base
  has_many :hierarchies
  has_many :families, :through => :hierarchies
  has_many :family_members,
           -> { group('families.rank').order('families.order ASC') },
           through: :families, source: :users
end

      



And then it is very easy to get all members of the current user:

current_user.family_members

+3


source


If by family members you mean family models, you can do something like

current_user.families.order(:order).group_by(&:rank)

      



If by your family members you mean users belonging to the same families as the current user, then it gets a little more complicated because each user can have many families. This means that each user can have multiple orders and multiple ranks.

+3


source


You can try something like this

For group From:

User.group(:name)
=> SELECT "users".* FROM "users" GROUP BY name
Returns an array with distinct records based on the group attribute:

      

For order:

User.order('name')
=> SELECT "users".* FROM "users" ORDER BY name

      

You may want to reference api.rubyonrails.org

0


source







All Articles