Skip to content

Instantly share code, notes, and snippets.

@jonduarte
Created June 26, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonduarte/c54146cb7e00f0045193aad739301c13 to your computer and use it in GitHub Desktop.
Save jonduarte/c54146cb7e00f0045193aad739301c13 to your computer and use it in GitHub Desktop.
class UserDiscount < ApplicationRecord
belongs_to :user
belongs_to :discount
def self.invalid_user_discounts
UserDiscount.
joins("INNER JOIN discount_segments ON user_discounts.discount_id = discount_segments.discount_id").
joins("INNER JOIN user_segments ON user_discounts.user_id = user_segments.user_id").
where("user_segments.segment_id <> discount_segments.segment_id")
end
def self.clean_user_discounts!
invalid_user_discounts.find_each do |user_discount|
user_discount.destroy
end
end
# Creates UserDiscounts when a user belongs to a segment and that segment has a discount
def self.create_user_discounts
query = UserSegment.
joins("INNER JOIN discount_segments ON user_segments.segment_id = discount_segments.segment_id").select(:id, :discount_id, :user_id)
query.find_each do |user_and_discount_segment|
UserDiscount.find_or_create_by(
discount_id: user_and_discount_segment.discount_id,
user_id: user_and_discount_segment.user_id)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment