Search code examples
rubymodelsequel

Improving Ruby Sequel Model Code


I have the following Model that retrieves an object known as GroupUser, which are as the name suggestions, a Group of Users:

[# < Model::GroupUser @values = {: id => 24,
  : user_id => 8,
  : group_id => 3,
  : from_group_id => 3
} > , # < GroupUser @values = {: id => 27,
  : user_id => 9,
  : group_id => 3,
  : from_group_id => 3
} > , # < GroupUser @values = {: id => 36,
  : user_id => 7,
  : group_id => 3,
  : from_group_id => 3
} > ]

I'd like to turn this GroupUser into their respective e-mail addresses (each User has an associated email property)

So I did the following:

users = []
group_users = Model::GroupUser.where(:group_id => self[:address]).map(:user_id)
group_users.each do |user|
  users << Model::User.where(id: user).first.email
end
users

It works.. But I feel like with how many elegant ways to do stuff in Ruby, this could be written in a more elegant way.


Solution

  • What comes to mind is this, essentially packing everything into a single map loop:

    users = Model::GroupUser.where(:group_id => self[:address]).map do |group_user|
      Model::User.where(id: group_user[:user_id]).first.email
    end
    

    If you set up the associations in your Sequel models, you can use group_user.user.first.email within the loop. Also, in that case, you may want to eager load the association for better performance: users = Model::GroupUser.eager(:user).where....