Ruby [如何从日期对象获取最后的历史记录]

时间:2017-10-20 10:02:10

标签: ruby-on-rails ruby postgresql activerecord rails-activerecord

我有

  

顺序

+-----+----------+------+-----------+------------+
| id  | id_reff  | pay0  | last_pay  |    date    |
+-----+----------+------+-----------+------------+
|  9  | 0110123  |   7  |        6  | 2017-10-20 |
|  8  | 0110123  |   6  |        5  | 2017-10-19 |
|  6  | 0110123  |   5  |        4  | 2017-10-15 |
|  5  | 0110123  |   4  |        3  | 2017-10-12 |
|  3  | 0110123  |   3  |        2  | 2017-10-08 |
|  2  | 0110123  |   2  |        1  | 2017-10-01 |
+-----+----------+------+-----------+------------+
  

客户

+----+---------+------+
| id | id_reff| name |
+----+---------+------+
|  1 | 110123 | jon  | <<<
|  2 | 110124 | jin  |
|  3 | 110125 | jun  |
|  4 | 110126 | jan  |
|  5 | 110127 | jack |
|  6 | 110128 | jick |
+----+---------+------+
  

Controller:customers_controller.rb

def get_history
  render json: {
       customer: Customer.find_by(id_reff: params[:id_reff]),
       bill: Order.where(id_reff: params[:id_reff]).last
end
  

订购_Form.rb

pay0 :
last_pay : <get from previous pay0>
etc
etc

问题: 如果我创建编辑任何订单,则.last给我这个

customer:  | 1 | 110123 | jon |

bill: | 9 | 0110123 | 7 |  6 | 2017-10-20 |

======

if i edit : order[id: 8][date: 2017-10-19]
i should get
    >> order.date = 2017-10-15 ; order.pay0 = 5

or

if i edit order[id: 5][date: 2017-10-12] 
i should get
    >> order.date = 2017-10-08 ; order.pay0 = 3

======

  

请帮我在customers_controller.rb重建 get_history 操作

     

rails 4.2.3

     

ruby​​ 2.3.3

2 个答案:

答案 0 :(得分:1)

当您调用.last时,它将返回具有更高ID的记录。

在特定情况下,您可以为Order模型添加自定义范围,例如:

class Order < ActiveRecord::Base
  # ...
  scope :most_recent, ->() { order(date: :desc).first }
end

您必须实施的唯一变更是:

def get_history
  render json: {
       customer: Customer.find_by(id_reff: params[:id_reff]),
       bill: Order.where(id_reff: params[:id_reff]).most_recent
end

请注意,假设您每个日期id_reff只有一个订单

,此解决方案可以正常运行

有关进一步说明,请尝试查看Rails文档中的scopes

答案 1 :(得分:0)

  

如果我编辑:订单[id:8] [日期:2017-10-19]

假设您可以访问order的{​​{1}}和id,那么您可以拥有这样的范围

date

然后你可以在控制器中调用它

scope :previous_order, -> { order(date: :desc).first }