Skip to content

Instantly share code, notes, and snippets.

@heratyian
Created June 26, 2024 21:06
Show Gist options
  • Save heratyian/e09715b75345386abcc16923a86d6664 to your computer and use it in GitHub Desktop.
Save heratyian/e09715b75345386abcc16923a86d6664 to your computer and use it in GitHub Desktop.

offer right

a buyer to seller marketplace

messages

  • id
  • created_at
  • updated_at
  • sender_id (user)
  • recipient_id (user)
  • item_id
  • body
class Message < ApplicationRecord
  belongs_to :sender, class_name: 'User', foreign_key: 'sender_id'
  belongs_to :recipient, class_name: 'User', foreign_key: 'recipient_id'
  belongs_to :item

  validates :body, presence: true
end

items

  • id
  • created_at
  • updated_at
  • title
  • price
  • seller_id (user)
  • description
  • category_id
  • buyer_id (user)
  • image

associations

class Item < ApplicationRecord
  belongs_to :seller, class_name: 'User', foreign_key: 'seller_id'
  belongs_to :buyer, class_name: 'User', optional: true, foreign_key: 'buyer_id'
  belongs_to :category
  has_many :messagess

  validates :title, :price, :seller, :category, presence: true

  scope :available, -> { where(buyer_id: nil) }
  scope :sold, -> { where.not(buyer_id: nil) }
end

users

  • id
  • created_at
  • updated_at
  • email
  • password
  • name
  • location
class User < ApplicationRecord
  has_many :sent_messages, class_name: 'Message', foreign_key: 'sender_id'
  has_many :received_messages, class_name: 'Message', foreign_key: 'recipient_id'

  def messages
    Message.where("sender_id = :id OR recipient_id = :id", id: self.id)
  end

  def conversations
    messages.includes(:item).group_by(&:item)
  end

  has_many :items, class_name: 'Item', foreign_key: 'seller_id'
  has_many :bought_items, class_name: 'Item', foreign_key: 'buyer_id'
  has_many :interested_items, through: :sent_messages, source: :item

  has_many :contacts, through: :received_messages, source: :sender

  validates :email, presence: true, uniqueness: true
  validates :name, presence: true
  validates :location, presence: true
end

categories

  • id
  • created_at
  • updated_at
  • name
class Category < ApplicationRecord
  has_many :items
  has_many :available_items, -> { available }, class_name: "Item"
  has_many :sold_items, -> { sold }, class_name: "Item"

  validates :name, presence: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment