1

I have the following code:

wedding = Wedding.where(location_id: user_params[:locationId])
wedding.map(&:guests).each do |member|
  user_ids << member.ids
end

In my case :guests is a active record table, but I have a couple that I would like to pass thru map to generate the user_ids

So it would be array of methods like this, that I would like to pass: [guests, bride, etc etc]

It would be even better if I could pass the whole array, but otherwise if I can step through the array of methods that would be great too.

Any ideas?

EDIT: I'm trying this with no luck.. I get: NameError (wrong constant name guests):

roles = ["guests"]
  wedding = Wedding.where(location_id: user_params[:locationId])
  roles.each do |role|
    clazz = Kernel.const_get(role)
    wedding.map(&:clazz).each do |member|
      user_ids << member.ids
    end
 end
ToddT
  • 3,084
  • 4
  • 39
  • 83
  • Have you tried the .send method? – PhiAgent Oct 09 '20 at 17:43
  • check my answer to see if that works for you – PhiAgent Oct 09 '20 at 17:56
  • Can you please explain your schema a bit better? You want to collect all the guests at a wedding location (regardless of the actual wedding?) so you will end up with multiple brides/grooms from different weddings and all the the guests is that the intent? – engineersmnky Oct 09 '20 at 20:33

1 Answers1

2

Below, i pass an array of methods to members of the array weddings:

weddings = Wedding.where(location_id: user_params[:locationId])

# array with methods you're interested in
methods=[:guests, :bride]

# looping through the weddings array
weddings.each do |wedding|
  
#   looping through the methods array
  methods.each do |method|
    
#     for each wedding, passing every method to the wedding
    members=wedding.public_send(method)
    members.each do |member|
      
#       storing the values
      user_ids << member.ids
    end
  end
end


PhiAgent
  • 158
  • 6
  • 1
    it's better to use `#public_send` instead of `#send` :) – Oleksandr Holubenko Oct 09 '20 at 17:53
  • Oh i see, why is that? – PhiAgent Oct 09 '20 at 17:54
  • 1
    Here is a good [answer](https://stackoverflow.com/a/36152851/4057366) why :) – Oleksandr Holubenko Oct 09 '20 at 17:57
  • Oh i see, so public send is for preservation of encapsulation while send bypasses that. Thanks @AlexGolubenko – PhiAgent Oct 09 '20 at 18:01
  • 1
    Additionally I would not recommend [`methods`](https://ruby-doc.org/core-2.5.0/Object.html#method-i-methods) or [`method`](https://ruby-doc.org/core-2.5.0/Object.html#method-i-method) as local variable names since both of these are actually "methods". Furthermore the map process is intensive for the desired result. – engineersmnky Oct 09 '20 at 20:29
  • yes you have a point. i actually had some slight discomfort naming them because of the reason you just mentioned. However, i figured in this scenario, it'll help the question author better understand so why not. – PhiAgent Oct 10 '20 at 00:46