开发者

Rails Given an array of objects from a db, is there a way to get an item in the array w/o having to rehit the db?

开发者 https://www.devze.com 2023-04-05 19:34 出处:网络
Given: @votes (user_id, option_id) If do: @project.votes I get all the votes for that project. If I then want to see what the current user voted for I have to do:

Given:

@votes (user_id, option_id)

If do: @project.votes I get all the votes for that project.

If I then want to see what the current user voted for I have to do:

Votes.where(:user_id => current_user.id).first

This is a record that's already in the @project votes query. Is there a way I can find the record in that first query w/o having to rehit the d开发者_JAVA技巧b?

Thanks


You can just use the regular ruby Enumerable#select method:

@votes = project.votes.all
# ... other code ...
current_user_votes = @votes.select{ |v| v.user_id == current_user.id }

This will return an array of all the user's votes for the project. If the user is only allowed one vote, and you want a single value, not an array, just use .first like so:

@votes = project.votes.all
# ... other code ...
current_user_vote = @votes.select{ |v| v.user_id == current_user.id }.first
0

精彩评论

暂无评论...
验证码 换一张
取 消