2015-10-15 55 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

相關問題