Ruby on Rails:通过模型方法访问和扩展SQL查询

时间:2014-07-07 02:05:38

标签: ruby-on-rails

我正在处理的Ruby on Rails应用程序有一个exchange_rate表,我希望在进行计算时将其转换为另一种货币。该表如下所示:

id | base_currency_id | currency_id | exchange_rate |
---+------------------+-------------+---------------+
2  |                1 |           2 |        0.9345 |
3  |                1 |           3 |        0.5000 |

exchange_rate模型如下所示:

class ExchangeRate < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
  validates :base_currency_id, :currency_id, :exchange_rate, presence: true
  ...
  def self.matching_exchange_rate(base_currency)
    ExchangeRate.where("base_currency_id = ?",base_currency)
  end 

  # Commented out as I can't get it to work yet:
  # def self.matching_exchange_rate (base_currency, target_currency_id)
  #  where("base_currency_id = ?",base_currency " and currency_id = ?",target_currency_id)
  # end 

我一直在调用/调用不完整但正常工作的函数matching_exchange_rate,如下所示:

x_rate = ExchangeRate.matching_exchange_rate(user_currency_id)
puts "x_rate = " + x_rate.to_s

在日志中显示为:

x_rate = #<ExchangeRate::ActiveRecord_Relation:0x0000010b434c78>

我很乐意帮助解决以下任何一个问题:
(1)如何更改matching_exchange_rate方法以使其使用两个输入参数?我尝试了大量不同的组合 - 其中一个在上面的注释掉的代码中 - 但到目前为止我没有运气。
(2)如何从返回值访问exchange_rate? (例如,ActiveRecord_Relation

提前感谢您的帮助, 皮埃尔

1 个答案:

答案 0 :(得分:1)

您可以使用pluck选择提供条件的exchange_rate,如下所示:

def self.matching_exchange_rate(base_currency, target_currency_id)
  where(
    "base_currency_id = ? and currency_id = ?", base_currency,target_currency_id
  ).pluck(
    'exchange_rate'
  ).first
end

上面的代码替换了您注释掉的方法。就您发布的以下输出而言:

x_rate = #<ExchangeRate::ActiveRecord_Relation:0x0000010b434c78>

where返回ActiveRecord::Relation。您可以在AR查询中使用first方法来引用您可以在其上调用ExchangeRate的第一个exchange_rate记录,如下所示:

x_rate = ExchangeRate.matching_exchange_rate(user_currency_id).first.exchange_rate
puts "x_rate = " + x_rate.to_s