From ca6a573c0a05a68a94ce8ce6b741649d81a1179c Mon Sep 17 00:00:00 2001 From: Matchu Date: Fri, 28 Jul 2023 15:06:33 -0700 Subject: [PATCH] Add user:owns/wants back to item search Not so bad, using a condition on `has_many` `through` was a cute trick!! --- app/models/item/search/query.rb | 24 ++++++++++++++++++++++++ app/models/user.rb | 6 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/app/models/item/search/query.rb b/app/models/item/search/query.rb index 66839850..a3751851 100644 --- a/app/models/item/search/query.rb +++ b/app/models/item/search/query.rb @@ -58,6 +58,22 @@ class Item filters << (is_positive ? Filter.fits(pet_type.body_id, color_name, species_name) : Filter.not_fits(pet_type.body_id, color_name, species_name)) + when 'user' + if user.nil? + message = I18n.translate('items.search.errors.not_logged_in') + raise Item::Search::Error, message + end + case value + when 'owns' + filters << (is_positive ? + Filter.user_owns(user) : + Filter.user_wants(user)) + when 'wants' + else + message = I18n.translate('items.search.errors.not_found.ownership', + keyword: value) + raise Item::Search::Error, message + end when 'is' case value when 'nc' @@ -151,6 +167,14 @@ class Item self.new Item.not_fits(body_id), "-fits:#{value}" end + def self.user_owns(user) + self.new user.owned_items, 'user:owns' + end + + def self.user_wants(user) + self.new user.wanted_items, 'user:wants' + end + def self.is_nc self.new Item.is_nc, 'is:nc' end diff --git a/app/models/user.rb b/app/models/user.rb index f74407e0..4abdd054 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -6,7 +6,11 @@ class User < ActiveRecord::Base has_many :closet_hangers has_many :closet_lists - has_many :closeted_items, :through => :closet_hangers, :source => :item + has_many :closeted_items, through: :closet_hangers, source: :item + has_many :owned_items, -> { where(ClosetHanger.arel_table[:owned].eq(true)) }, + through: :closet_hangers, source: :item + has_many :wanted_items, -> { where(ClosetHanger.arel_table[:owned].eq(false)) }, + through: :closet_hangers, source: :item has_many :contributions has_many :neopets_connections has_many :outfits