1
@matched = [1, 2, 3]

Where each integer represents the id of an ActiveRecord object in the Inventory class. As a next step, I want to look at each of those objects and obtain the email of the parent User, but I'm not sure how to do it. Ideally I'd write something like:

Inventory.where(id: @matched).user.email

Because certainly, this statement would work if I only had a single id to look up. Since that doesn't work, I'm instead doing this

@email = []
@matched.each do |i|
   @email << Inventory.find_by_id(i).user.email
end

Just wondering if there's an easier way.

Thanks!

2 Answers 2

2

If you only need the email addresses then you can use the pluck method:

Inventory.where(id: @matched).joins(:user).pluck("users.email")
Sign up to request clarification or add additional context in comments.

2 Comments

This is way better than my answer. I'm such a hacker I swear
I was going to post an answer with Array#map but this is the best solution.
0
class Inventory

  def self.with_ids(ids) 
    sql = @matched.map{|id| "id = #{id}"}.join(" OR ")
    where(sql)
  end

  def parent_email
    user.email
  end
 end

Inventory.with_ids(@matched).map(&:parent_email)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.