Rails如何描述多对多的限制

时间:2015-06-24 05:00:17

标签: ruby-on-rails

我有这个:


model listing:
  has_many: restrictions
model user:
  has_many: restrictions
model restriction:
 belongs_to: :user
 belongs_to: :listing

默认情况下,所有用户都可以看到所有列表,因为列表和用户之间没有关系,但我想限制用户如果限制表上有记录,则按每个列表。

例如:

如果记录 restrictions.user_id:2 restrictions.listing_id:5 退出,具有ID为2的用户将会看到所有列表< strong> 列表,ID为

如何使用rails进行/描述?

3 个答案:

答案 0 :(得分:0)

我想到的是在Listing模型中有一个范围,它将排除受限制的列表:

scope :accessible_listings, -> { where('id != ?',Restriction.where(user_id: current_user.id).map(&:listing_id)) }

答案 1 :(得分:0)

我不是一个has_many关联,也许你可以定义一个方法来做你想做的事情

    class User
      def listings
        Listing.where.not(id: ((self.restrictions.map &:listing).uniq.map &:id))
      end
    end

答案 2 :(得分:0)

正如@nesiseka回答的那样,稍微改动一下,使用rails where.not

scope :accessible_listings, ->(user) { where.not(id: Restriction.where(user_id: user.id).map(&:listing_id) ) }