【问题标题】:How to show users how many downloads they made Rails 4如何向用户显示他们下载了多少 Rails 4
【发布时间】:2015-07-27 23:19:54
【问题描述】:

在我的应用中,当买家从卖家那里购买商品时,买家的积分会归卖家所有。 这是控制器中的逻辑(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.注册一个下载模型Download.create(user: current_user, downloadable: thing),2.显示,来自Rails脚手架
  • 所以基本上你建议添加到我的“演出”模型中,一个名为“下载”的列,在我的演出模型中,下面(上面的代码),创建类似`def download--- - @gigs = Download.create(user: current_user, download: gig)---end ` 并且在视图中类似于 ?
  • 不,不完全是,嗯,我不明白。
  • 这是我从您的建议jsfiddle.net/ken1vaqz 中了解到的,请注意我是根据您的建议写的。为了让自己更清楚,我基本上需要保留交易记录,即买家在买东西时制造。

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


【解决方案1】:

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

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

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

【讨论】:

  • 如果我的应用没有买家和卖家,只有 current_user 和用户怎么办?这就是我在用户和 current_user 之间进行积分交换的方式(因为在我的应用中,任何用户都可以成为卖家和买家)。如何更改您的代码?
  • 我认为您不太了解这一点 - 在此示例中,任何用户都可以多次成为买家和卖家。 seller_idbuyer_id 都只是用户的 ID。要在用户之间建立多对多关系,您需要一个联接表,该表将双方存储在事务中。您可以将列和关系称为 user_idcurrent_user_id - 实际上称它们为买方和卖方只会让您的代码更容易对其他人真正有意义。
  • 关联成功了,但我不能显示演出的标题和图像,我只能.count方法,下载多少。请看我的“编辑”从问题。感谢您的帮助,我尝试了整整一夜以了解您的建议。终于几乎明白了)
  • 你能问一个新问题吗?这实际上不再属于原始问题的范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2022-11-04
相关资源
最近更新 更多