Ofertas favoritas con rieles

I have Offers table and Favorites table with offer_id. When I display all Offers at the screen I want to display "yellow star" in favorites offers

I get Favorites as:

  scope :in_favorites, lambda { |user_id|
    favorites = Favorite.where(:user_id => user_id).map(&:offer_id)
    if favorites.size > 0
      where :id => favorites
    end
  }

How to check if Offer exists in Favorites

preguntado el 27 de agosto de 11 a las 15:08

1 Respuestas

I don't know if I understood your question correctly, but your should be able to check if an offer is in the favorites of an user with :

# Example with the user n°1
Offer.in_favorites(1).include?(offer)

Another way to model your offers would be to use a has_many :through asociación:

class User < ActiveRecord::Base
    has_many :favorites
    has_many :favorite_offers, :through => :favorites, :source => :offer
end

You could then do :

# user is an instance of User
user.favorite_offers.include?(offer)

# same thing, only SQL. A bit less readable, but doesn't load all the user's favorites
!user.favorite_offers.where(:id => offer.id).empty?

Espero que esto ayude.

Respondido 28 ago 11, 05:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.