1

I have a method on my Node model that looks like this:

  def users_tagged
    @node = self
    @tags = @node.user_tag_list
    @users = @tags.each do |tag|
      User.find_by email: tag
    end
  end

What I would like to happen is for the @users object to be a collection of User records, but it simply returns a list of email addresses.

This is what this Node object looks like:

> n
=> #<Node id: 6, name: "10PP Form Video", family_tree_id: 57, user_id: 57, media_id: 118, media_type: "Video", created_at: "2015-03-09 20:57:19", updated_at: "2015-03-09 20:57:19", circa: nil, is_comment: nil>
> n.user_tags
=> [#<ActsAsTaggableOn::Tag id: 4, name: "gerry@test.com", taggings_count: 1>, #<ActsAsTaggableOn::Tag id: 3, name: "abc@test.com", taggings_count: 1>]
[135] pry(main)> n.user_tag_list
=> ["gerry@test.com", "abc@test.com"]

But when I try to execute that method, this is what I get:

> n.users_tagged
  ActsAsTaggableOn::Tag Load (0.5ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'user_tags' AND taggings.tagger_id IS NULL)  [["taggable_id", 6], ["taggable_type", "Node"]]
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."email" = 'gerry@test.com' LIMIT 1
  User Load (0.5ms)  SELECT  "users".* FROM "users"  WHERE "users"."email" = 'abc@test.com' LIMIT 1
=> ["gerry@test.com", "abc@test.com"]

Why does it not return the entire record?

marcamillion
  • 32,933
  • 55
  • 189
  • 380

1 Answers1

5

Well, you need to use Array#collect, not the Array#each :

def users_tagged
  @node = self
  @tags = @node.user_tag_list
  @users = @tags.collect do |tag|
    User.find_by email: tag
  end
end

Read this - what's different between each and collect method in Ruby

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317