【问题标题】:Rails using a variable find conditionRails 使用变量查找条件
【发布时间】:2011-12-12 22:15:11
【问题描述】:

我正在使用 Braintree 在我的 Rails 应用程序中管理订阅。

我有一个订阅模型,它存储了 Braintree 客户 ID 和订阅 ID。

我想在我的订阅模型中过滤有效订阅。到目前为止我有

def find_active_subscriptions
@active_subscriptions = Braintree::Subscription.search do |search|
  search.status.is "Active"
end

但现在我想使用 @active_subscriptions 中的订阅 ID 来查找我的本地订阅模型中具有相同订阅 ID 的所有对象,并将其放入一个变量中,例如 @local_active_subscriptions。

我必须这样做的原因是使用本地信息来访问 Braintree::Address 并且只提取活动地址。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails find conditional-statements braintree


    【解决方案1】:

    如果您拥有 @active_subscriptions,您可以将所有 id 收集到一个数组中,并将它们直接传递给您本地订阅模型的 find 方法。我不知道你在这里使用什么属性,所以我只是做一些猜测:

    @active_subscription_ids = @active_subscriptions.collect(&:subscription_id)
    @local_active_subscriptions = LocalSubscriptionModel.find(@active_subscription_ids)
    

    【讨论】:

      【解决方案2】:

      我不确定 Braintree::Subscription.search 返回什么,但如果它类似于 ActiveRecords,你可以使用类似的东西:

      @local_active_subscriptions = Subscription.where("id IN(?)", @active_subscriptions.map{ |act_subs| act_subs.id })
      

      .map 函数应该将所有 ID 放入一个数组中,然后 ActiveRecord 查询将在您的订阅表中查找 ID 在该数组中的所有订阅。 我不确定在 Braintree::Subscriptions 上的映射;我从来没用过。

      编辑

      就像 ctcherry 说的,你也可以用 find 进行搜索。而且我猜 collect 也适合将 id 映射到数组中。你也可以使用@active_subscriptions.map(&:id)

      【讨论】:

        猜你喜欢
        • 2011-05-06
        • 2011-02-15
        • 2012-10-11
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多