收藏夹提供rails

时间:2011-08-27 15:10:33

标签: ruby-on-rails-3 activerecord

我有offer表和收藏夹表,上面有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
  }

如何检查收藏夹中是否存在优惠

1 个答案:

答案 0 :(得分: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?

希望这有帮助。