How can I create array of strings or a hash from ActiveRecord result set?

Is there a way to do that in a single shot? Or what’s the most
efficient way of doing that?
I’ve researched a lot but did not find out how to do it yet.
Any help will be much appreciated.

Example (the syntax is not correct is some cases):

  • Models:
    User belongs_to :group
    Group has_many :users

  • Controller:
    #User columns: id, email, group_id, etc.
    @users = User.find(:all, :order => “group_id”)

    #Things I wanted to have:
    #@emails1 = array of all emails, i.e. [email_1,email_2, etc]
    #@emails2 = string with all emails joined, i.e.
    “email_1,email_2,email_3,etc”
    #@emails3 = hash/map with all emails grouped by group_id, i.e.
    [group_id_1 => [email_1,email_2], group_id_2 =>
    [email_3,email_4,email_5],etc]

  • View:
    <%= mail_to ‘[email protected]’, ‘Email Everybody 1’, :subject =>
    ‘Subject’, :bcc => @emails1.join(’,’) %>
    <%= mail_to ‘[email protected]’, ‘Email Everybody 2’, :subject =>
    ‘Subject’, :bcc => @emails2 %>
    <%= mail_to ‘[email protected]’, ‘Email Group ’ + @group_id, :subject =>
    ‘Subject’, :bcc => @emails[@group_id].join(’,’) %>
    etc

@users = User.find(:all, :order => “group_id”)
@emails1 = @users.collect{|u| u.email}
@emails2 = @emails1.join ‘,’
@emails3 = {}
@users.each{|u| @emails3[u.group_id] ||= []; @emails3[u.group_id] <<
u.email}

There may be a more creative way to do the last one, but this should get
you started.

This is amazing. Works perfect.
Thanks!!!

On 9/26/07, eafonsof [email protected] wrote:

This is amazing. Works perfect.
Thanks!!!

The email array and string part are pretty much as William has shown.
For
the grouped email hash you can use the group_by method which is part of
enumerable. It’s a bit slower than manually doing it. But depending on
your tastes it might suit you better.

@emails3 = @users.group_by(&:group_id).each{ |email_array|
email_array.map!(&:email) }

HTH
Daniel

On Sep 26, 2007, at 12:49 AM, William P. wrote:

Group has_many :users
[group_id_1 => [email_1,email_2], group_id_2 =>

@users = User.find(:all, :order => “group_id”)
@emails1 = @users.collect{|u| u.email}
@emails2 = @emails1.join ‘,’
@emails3 = {}
@users.each{|u| @emails3[u.group_id] ||= []; @emails3[u.group_id] <<
u.email}

There may be a more creative way to do the last one, but this
should get
you started.

@users = User.find(:all, :order => “group_id”)
@emails1 = @users.map(&:email)

@emails2 = @emails1.join ‘,’

@emails3 = @users.inject(Hash.new {|h,k| h[k] = []}) {|h,u| h
[u.group_id] << u.email; h}

Well, that last one might be a bit too creative for some :wink:

-Rob

Rob B. http://agileconsultingllc.com
[email protected]