2015-10-15 38 views
-1

我得到了一个哈希数组。这些哈希中有一个唯一的用户标识。我需要返回所有用户的喜好的:基于用户标识返回所有哈希值作为密钥

p = Post.first 
all_likes = p.likes 

# This returns: [0][1][2] etc 
# inside a hash looks like: 
[0] #<Like:0x007f81d3dfb310> { 
id: => 4, 
user_id: => 1, 
like_sent: => 1 # this will always be one 
} 

让我们假设all_likes拥有众多用户,我需要user_id: 1的总like_sent。如何获得?

all_likes.find {|f| f["user_id"] = current_user.id } # this returns one hash. I need to return all if more is found. 

所以如果“杰森”喜欢后10次,我要抢他的总喜欢。 如何返回所有匹配哈希值。这是一个完美的问题。

+2

您是否尝试过'''all_likes.where ,current_user.id''' –

+0

至少你不是一般的失败!这样可行。想发布这个答案,我会接受吗? – Sylar

回答

1

尝试

all_likes.where 'user_id = ?', current_user.id 

而且find方法有一些不同的语法,是这样的: 'USER_ID ='

all_likes.find :all, :conditions => ['user_id = ?', current_user.id] 

docs

+1

请注意,散列风格的查找是从[Rails 4.0](http://guides.rubyonrails.org/4_0_release_notes.html#active-record-deprecations)折旧并在[Rails 4.1](https)中作为依赖项正式删除://github.com/rails/activerecord-deprecated_finders)。所以你的第一个答案是最一般的正确,但我会建议更新语法为'.where(user_id:current_user.id)' – engineersmnky