0

我有以下型号:

帐户

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

查询: 给定 a 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]]

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

4

2 回答 2

2

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

class User < ActiveRecord::Base
  has_many :members
  has_many :accounts, through: :members
end
于 2013-10-03T01:21:09.940 回答
1

为什么不做

u = User.take
a = u.accounts.find(id)
于 2013-10-02T22:34:35.860 回答