Gugubaight
Gugubaight

Reputation: 187

Rails 4: Model logic

A quick question:

I've got a FavoriteItem Model which includes :id :user_id :item_id

How can I check within a loop through all Items

- @items.each do |item|

... if the current_user has favorited an item?

=> For Example:

current_user.id == 243
item.id == 53

This db entry exists in FavoriteItems:

:id => 1, :user_id => 243, :item_id => 53

How can I check in my loop if this item got favorited by the current user?

I am grateful for all your help! Tell me if you need more information.

Upvotes: 0

Views: 49

Answers (2)

mu is too short
mu is too short

Reputation: 434965

You should be able to do this in a single database call:

item.favorited_items.where(:user_id => current_user).exists?

You could also wrap that up in a method on Item:

def favorited_by?(user)
  favorited_items.where(:user_id => user).exists?
end

and then say item.favorited_by?(current_user) in your loop.

If you're looping over a large number of items then you could precompute the current user's favorites to avoid n+1 queries.

Upvotes: 4

John Feltz
John Feltz

Reputation: 560

You can do it with map and include?

@items.each do |item|
  if item.favorited_items.map(&:user_id).include?(current_user.id)
    # yep, there's a match - do something
  end
end

If you're going to be using this functionality a lot, you probably want to create a scope on the items model.

Upvotes: 1

Related Questions