Ruby on rails 在RubyonRails中组织和映射记录

Ruby on rails 在RubyonRails中组织和映射记录,ruby-on-rails,Ruby On Rails,下面是一些文章的销售情况表 id | user_id | article_id | status 1 | 1 | 1 | 0 2 | 1 | 2 | 0 3 | 2 | 2 | 0 4 | 1 | 1 | 1 5 | 2 | 2 | 1 其中,status=0为未确认,status=1为已确认 逻辑如下:用户点击一个按钮购买一篇文章,然

下面是一些文章的销售情况表

id | user_id | article_id | status
1  | 1       | 1          | 0
2  | 1       | 2          | 0
3  | 2       | 2          | 0
4  | 1       | 1          | 1
5  | 2       | 2          | 1
其中,
status=0
未确认
status=1
已确认

逻辑如下:用户点击一个按钮购买一篇文章,然后一条记录以未确认状态保存在表中。付款确认后,另一条记录保存在表上,状态为“已确认”。这两条记录都保存在表上,以保留整个事务的时间线。
id
字段确定给定事务中最早的记录

在我的应用程序中,我想获得一份5篇最畅销文章的列表,以下是我迄今为止的做法:

# In articles_helper.rb

  def get_articles_sold
    # Fetch all Articles that are present in the Sales table
    sales = Article.where(id: Sale.select(:article_id).map(&:article_id))

    sold = []
    sales.each do |s|
      s.status.group_by(&:status).each do |status, sale|
        if status.to_sym == :confirmed
          sold << {article: s, sold: sale.count}
        end
      end
    end

    # Returns the sold array
    sold
  end

# In the Article model there's this Virtual Attribute 'status'
# It returns me the last status from a given transaction

def status
    sales = Sale.where(article_id: self.id).order(id: :desc)

    statuses = []

    sales.group_by(&:user_id).each do |user, sale|
      statuses << sale.first
    end

    statuses
  end

#In my application

@most_sold_articles = get_articles_sold.sort_by{|v| v[:sold]}.reverse
#在articles_helper.rb中
def获得商品销售
#获取销售表中的所有商品
sales=Article.where(id:Sale.select(:Article\u id).map(&:Article\u id))
售出=[]
销售。每件事|
s、 状态。分组依据(&:状态)。每个do状态,销售|
如果status.to_sym==:已确认

我想这应该可以

@articles = Article
  .joins(:sales)
  .select("articles.*, count(sales.article_id) as sold")
  .group('articles.id').order('sold DESC').limit(5)
如果您想要与答案中相同的格式

@most_sold_articles = @articles.map{|a| {article: a, sold: a.sold}}

#=> [
#=>   {article: #<some_article_entity>, sold: 100},
#=>   {article: #<some_article_entity>, sold: 80},
#=>   {article: #<some_article_entity>, sold: 75},
#=>   {article: #<some_article_entity>, sold: 66},
#=>   {article: #<some_article_entity>, sold: 30}
#=> ]   
@most_salled_articles=@articles.map{article:a,selled:a.selled}
#=> [
#=>{文章:#,售出:100},
#=>{文章:#,售出:80},
#=>{文章:#,售出:75},
#=>{文章:#,售出:66},
#=>{文章:#,售出:30}
#=> ]   

我建议
.order(“seld DESC”).limit(5)
这样您就不必反转列表了。。。我不敢相信我所有的代码都能轻松减少4行!!!我现在感觉很尴尬哈哈哈哈谢谢你们的回复伙计们,你们是最棒的:)
@most_sold_articles = @articles.map{|a| {article: a, sold: a.sold}}

#=> [
#=>   {article: #<some_article_entity>, sold: 100},
#=>   {article: #<some_article_entity>, sold: 80},
#=>   {article: #<some_article_entity>, sold: 75},
#=>   {article: #<some_article_entity>, sold: 66},
#=>   {article: #<some_article_entity>, sold: 30}
#=> ]