通过查询生成以下has_many的最有效方法是什么?

时间:2013-10-02 21:36:33

标签: sql ruby-on-rails activerecord orm

我有以下模特:

帐户

class Account < ActiveRecord::Base
  has_many :members
  has_many :users, through: :members
end

会员

class Member < ActiveRecord::Base
  belongs_to :account
  belongs_to :user
end

用户

class User < ActiveRecord::Base
  has_many :accounts, through: :members
end

查询: 给定User.id,找到该帐户。目前我这样做:

> u = User.take
User Load (1.5ms)  SELECT "users".* FROM "users" LIMIT 1
> id = Member.where(user_id: u.id).pluck(:account_id)
(0.8ms)  SELECT "members"."account_id" FROM "members" WHERE "members"."user_id" = 1
> a = Account.find(id)
Account Load (8.9ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1  [["id", 1]]

在给定用户的情况下,想知道是否有更好或更快的方法来查找帐户?

2 个答案:

答案 0 :(得分:2)

我不知道您的模型的详细信息,但根据错误,您似乎需要members模型中的User关联:

class User < ActiveRecord::Base
  has_many :members
  has_many :accounts, through: :members
end

答案 1 :(得分:1)

为什么不

u = User.take
a = u.accounts.find(id)