2011-08-27 76 views
1

我已經爲offer_id提供了表格和收藏夾表格。 當我顯示在屏幕 所有優惠我想顯示「黃星」,在收藏提供帶欄杆的收藏夾優惠

我得到收藏爲:

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

如何檢查是否在收藏夾中存在

回答

2

我提供不知道我是否正確理解你的問題,但你應該能夠檢查一個報價是否在用戶的收藏夾中:

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

另一種方式來模擬你的報價是使用has_many :through協會:

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

那麼你可以做:

# 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? 

希望這有助於。