0
生成以下的has_many我有以下型號:什麼是最efficent方式,通過查詢
帳戶
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]]
知道是否有一個更好更快的方式找到客戶,給用戶?
我試過了,但它給'ActiveRecord :: HasManyThroughAssociationNotFoundError:無法找到關聯:模型用戶中的成員' – CuriousMind