【问题标题】:ActiveRecord::Relation print specific attributeActiveRecord::Relation 打印特定属性
【发布时间】:2016-01-19 11:59:08
【问题描述】:

我有一个 ActiveRecord::Relation between:

订单类别:

has_many :transactions, :class_name => "OrderTransaction"

OrderTransaction 类:

belongs_to :order    
serialize :params

ActiveRecord::Relation [#OrderTransaction id: 5, order_id: 11, action: "purchase", amount: 26044, success: true, authentication: "8V863650823585301", message: "Success", params: {"timestamp" =>“2015-10-16T23:11:09Z”、“ack”=>“成功”、“correlation_id”=>“9b5eb7051dbe3”、“版本”=>“72”、“构建”=>“18308778”、 "amount"=>"260.44", "amount_currency_id"=>"USD", "avs_code"=>"X", "cvv2_code"=>"M", "transaction_id"=>"8V863650823585301", "Timestamp"=> "2015-10-16T23:11:09Z", "Ack"=>"Success", "CorrelationID"=>"9b5eb7051dbe3", "Version"=>"72", "Build"=>"18308778", "金额"=>"260.44", "AVSCode"=>"X", "CVV2Code"=>"M", "TransactionID"=>"8V863650823585301"}, created_at: "2015-10-16 23:11:09",更新时间:“2015-10-16 23:11:09”]

我正在尝试在 irb 控制台中打印 params[:transaction_id] 但我找不到正确的方法来执行此操作。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    应该这样做:

    OrderTransaction.where(message: "Success").map { |p| p['params']['transaction_id'] }
    

    只得到一个transaction_id

    x = OrderTransaction.where(message: "Success").last
    x['params']['transaction_id']
    

    【讨论】:

    • 假设我已将所有 ActiveRecord::Relation 定义为名为 x 的变量。怎么表达?
    • 你的意思是,x = params 那么你可以这样做:x.map { |p| p['transaction_id'] } 这会给你所有的transaction_ids。如果您有任何其他问题,请告诉我。
    • 我收到此错误:NoMethodError: undefined method 'params' for #<OrderTransaction::ActiveRecord_Relation
    • 你如何得到OrderTransaction::ActiveRecord_Relation,你能得到那个代码吗?
    • 我通过x = OrderTransaction.where(message: "Success").last找到关系
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多