如何使用活动记录从foren表中进行选择

时间:2013-07-11 20:36:31

标签: ruby-on-rails postgresql activerecord

我有2个表,帐户和订阅。所有帐户都有订阅,当我这样做时

Account.last.subscription.name
  Account Load (0.4ms)  SELECT "accounts".* FROM "accounts" ORDER BY "accounts"."id" DESC LIMIT 1
  Subscription Load (0.2ms)  SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."account_id" = 73 LIMIT 1
"free"

但我试图让所有设置为免费的帐户。

1 个答案:

答案 0 :(得分:3)

你的问题中没有细节,所以我们必须做出一些假设。我们假设Subscription有一个布尔free列。

# Rails 4
Account.joins(:subscriptions).where(free: true).references(:subscriptions)

# Rails 3
Account.joins(:subscriptions).where('subscriptions.free = ?', true)

如果我们假设free是帐户属性:

Account.where(free: true)

如果您想提取订阅详情:

Account.where(free: true).includes(:subscriptions)