【问题标题】:rails 4 activerecord update multiple attributesrails 4 activerecord 更新多个属性
【发布时间】:2014-05-07 17:11:50
【问题描述】:

我对我尝试对 Rails 4 / Activerecord 进行的更新感到困惑。我正在开发的应用程序使用 Stripe 来处理订阅,这个函数应该处理更新的订阅(stripe customer.subscription.updated 事件):

# passing in a stripe webhook event object
# event.data.object.current_period_end = 1402100302
subscription = Subscription.find_by(stripe_id: event.data.object.id)
plan = Plan.find_by(stripe_name: event.data.object.plan.id)

subscription.update(expires_at: event.data.object.current_period_end, plan_id: plan.id)

这一切似乎都很清楚,当我在 rails 控制台中执行各个行时,我得到了subscriptionplan 等的有效数据。但是,update 没有按预期工作。以下是在 rails 控制台中执行的查询针对 update 行显示的内容:

SQL (0.7ms)  UPDATE "subscriptions" SET "expires_at" = $1, "updated_at" = $2 WHERE "subscriptions"."id" = 23  [["expires_at", nil], ["updated_at", Wed, 07 May 2014 17:09:25 UTC +00:00]]
   (15.9ms)  COMMIT
=> true

expires_atnil,第二个值plan.id 甚至没有被传递到查询中。我应该如何处理这个更新?

【问题讨论】:

  • 你确定 'event.data.object.current_period_end' 不为零吗?另外,plan_id 是订阅模型的属性吗?此外,最好将计划对象分配给计划关系并让订阅模型定义计划外键。
  • 嗨——是的,# event.data.object.current_period_end = 1402100302plan_idsubscriptions 的外键。问题在于,stripe 使用的计划 ID 与本地存储的 ID 不同,所以据我所知,我们必须查找它。

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


【解决方案1】:

看起来event.data.object.current_period_end 只需像这样转换为Time

subscription.update(expires_at: Time.at(event.data.object.current_period_end), plan_id: plan.id)

这很令人困惑,因为在 create_subscription 事件中我执行完全相同的更新,通过 webhook 数据设置 expires_at,并使用相同的值/时间戳来设置 expires_at 值。

看起来 rails 足够聪明,可以知道 update 何时不会更改值 - 因此它会将其排除在查询之外。这是我与plan_id 混淆的部分原因——expires_at 日期已更改,但计划并未更改——因此 rails 将更新语句的那部分从 sql 中删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多