我的Node
模型上有一个方法如下:
def users_tagged
@node = self
@tags = @node.user_tag_list
@users = @tags.each do |tag|
User.find_by email: tag
end
end
我希望发生的是@users
对象是User
条记录的集合,但它只返回一个电子邮件地址列表。
这是Node
对象的样子:
> 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"]
但是当我尝试执行该方法时,这就是我得到的:
> 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"]
为什么不返回整个记录?
答案 0 :(得分:5)
嗯,您需要使用Array#collect
,而不是Array#each
:
def users_tagged
@node = self
@tags = @node.user_tag_list
@users = @tags.collect do |tag|
User.find_by email: tag
end
end
阅读本文 - what's different between each and collect method in Ruby