如何向用户显示他们制作Rails 4的下载量

时间:2015-05-15 22:17:23

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller model

在我的应用中,当买家从卖家那里购买东西时,买家的积分会转到卖家手中。 这是控制器中的逻辑(gig =是产品)

def downloadpage
    ActiveRecord::Base.transaction do
      if current_user.points >= @gig.pointsneeded 
        current_user.points -= @gig.pointsneeded
        @gig.user.points += @gig.pointsneeded
        current_user.save
        @gig.user.save
        redirect_to @gig.boxlink
      else
        redirect_to :back, notice: "You don't have enough points"
      end
    end
  end
  

问题:如何创建列出用户下载/购买的网页?

1 个答案:

答案 0 :(得分:1)

您需要一个联接表来创建产品和用户之间的多对多关系。

database illustration

在这种情况下,您可能希望使用“连接模型”来设置关系 - 这是一个描述用户和产品之间关系的模型。

class User < ActiveRecord::Base
  has_many :purchases, foreign_key: 'buyer_id'
  has_many :sales, foreign_key: 'seller_id', class_name: 'Purchase'
end

class Product < ActiveRecord::Base
  has_many :purchases
  has_many :buyers, through: :purchases
  has_many :sellers, through: :purchases
end

class Purchase < ActiveRecord::Base
  belongs_to :product
  belongs_to :buyer, class_name: 'User'
  belongs_to :seller, class_name: 'User'
end

查询示例:

user.purchases 
user.purchases.first.product
user.purchases.this_month

您需要修改控制器以执行以下操作:

def downloadpage
  ActiveRecord::Base.transaction do
    if current_user.points >= @gig.pointsneeded 
      @purchase = current_user.purchases.create(product: @gig, seller: @gig.user)
      if @purchase
       # ... transfer points between seller and buyer
      end
    end
  end
end

列出用户购买的操作可能如下所示:

class PurchasesController
  def index 
    @purchases = current_user.purchases
  end
end