Rails - 从字符串中调用方法

Rails - Call a method from within a string

我正在尝试调用我在字符串中定义的方法,该方法作为参数传递给 where 方法,如下所示:

existing_size = self.exchange_rates.where("? < date_valid", :time).size

方法是:

  def date_valid
    date = Date.today
    if(Time.now.hour >= HOUR)
      date += 1.day
    end
    date
  end

但是,我收到错误消息:

ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column "date_valid" does not exist
       LINE 1: ...xchange_rates"."prediction_id" =  AND ('time' < date_valid...

您似乎在 where 调用中交换了 time 属性和 date_valid 方法。这当然是假设 time 实际上是 exchange_rates table 中的一个列。以下应该适合您。

existing_size = self.exchange_rates.where("time < ?", date_valid).count

我还使用了 count 而不是 size 因为 count 在数据库中进行计算,而 size 在返回的 exchanged_rates关系。