Ruby on rails Rails如何描述多对多限制
我有这个:Ruby on rails Rails如何描述多对多限制,ruby-on-rails,Ruby On Rails,我有这个: model listing: has_many: restrictions model user: has_many: restrictions model restriction: belongs_to: :user belongs_to: :listing 默认情况下,允许所有用户查看所有列表,因为列表和用户之间没有关系,但如果限制表上有记录,我想限制每个列表的用户 例如: 如果record restrictions.user_id:2和restrictions.
model listing:
has_many: restrictions
model user:
has_many: restrictions
model restriction:
belongs_to: :user
belongs_to: :listing
默认情况下,允许所有用户查看所有列表,因为列表和用户之间没有关系,但如果限制表上有记录,我想限制每个列表的用户
例如:
如果record restrictions.user_id:2和restrictions.listing_id:5退出,则id为2的用户将看到除id为5的列表之外的所有列表
我如何用rails做到/描述这一点?我想到的是在清单模型中有一个范围,它将排除受限清单:
scope :accessible_listings, -> { where('id != ?',Restriction.where(user_id: current_user.id).map(&:listing_id)) }
我不认为这有很多联系,也许你可以定义一个方法来做你想做的事情
class User
def listings
Listing.where.not(id: ((self.restrictions.map &:listing).uniq.map &:id))
end
end
正如@nesiseka所回答的,只做了一点修改,使用rails where.not
scope :accessible_listings, ->(user) { where.not(id: Restriction.where(user_id: user.id).map(&:listing_id) ) }