简体   繁体   English

rails 4 activerecord更新多个属性

[英]rails 4 activerecord update multiple attributes

I'm puzzled by an update I'm attempting to do with Rails 4 / Activerecord. 我对Rails 4 / Activerecord所做的更新感到困惑。 The app I'm working on is using Stripe to handle subscriptions, and this function should deal with an updated subscription (stripe customer.subscription.updated event): 我正在使用的应用程序正在使用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)

This all seems clear, and when I execute the individual lines in a rails console, I get valid data for subscription , plan , etc. However, the update doesn't work as expected. 这一切似乎很清楚,当我在Rails控制台中执行各行时,我会获得有效的数据subscriptionplan等。但是, update无法按预期进行。 Here's what the query executed in the rails console shows for the update line: 这是在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_at is nil , and the second value, plan.id doesn't even get passed in to the query. expires_atnil ,第二个值plan.id甚至没有传递到查询中。 How should I handle this update? 我应该如何处理此更新?

Looks like the event.data.object.current_period_end just has to be converted to a Time like this: 看起来event.data.object.current_period_end只需转换为这样的Time

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

This is confusing since in the create_subscription event I do the update exactly the same, setting the expires_at via the webhook data, and using the same values / timestamp to set the expires_at value. 这很令人困惑,因为在create_subscription事件中,我执行的更新完全相同,通过webhook数据设置expires_at ,并使用相同的值/时间戳来设置expires_at值。

It also appears rails is smart enough to know when a value is not going to be changed by the update -- and it therefore leaves it out of the query. 看起来rails足够聪明,知道什么时候update不会更改值-因此将其排除在查询之外。 That was part of my confusion with the plan_id -- the expires_at date had changed, but the plan had not-- so rails was leaving that part of the update statement out of the sql. 那是我的困惑的部分plan_id -在expires_at日期已经改变,但这一计划已经不是-所以导轨离开的UPDATE语句的那部分的SQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM