Product orders between 2 users

后端 未结 3 1098
离开以前
离开以前 2021-01-06 02:29

I have three models: User, Product, Offer and a problem with the relationship between these models.

Scenario:

User 1 posts a product

3条回答
  •  忘掉有多难
    2021-01-06 02:55

    How about

    class User < ActiveRecord::Base
      has_many :products  # All products posted by this user
      has_many :offers    # All offers created by this user
    end
    
    class Product < ActiveRecord::Base
      belongs_to :user   # This is the user who posts the product (User 1)
      has_many :offers
    end
    
    class Offer < ActiveRecord::Base
      belongs_to :product
      belongs_to :user   # This is the user who creates the offer (User 2)
    
      # Use a 'state' field with values 'nil', 'accepted', 'rejected' 
    end 
    

    For your scenario:

    # User 1 posts a product
    product = user1.products.create
    
    # User 2 can send User 1 an offer with an price e.g $ 10
    offer = user2.offers.create(:product => product)
    
    # User 1 can accept or reject the offer
    offer.state = 'rejected'
    

    You could refine this depending on your needs - e.g. if the same product could be posted by different users.

提交回复
热议问题