【问题标题】:What is the most efficent way generate the following has_many through query通过查询生成以下has_many的最有效方法是什么
【发布时间】:2013-10-02 21:36:33
【问题描述】:

我有以下型号:

帐户

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]]

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

【问题讨论】:

    标签: sql ruby-on-rails activerecord orm


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      为什么不这样做

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

      【讨论】:

      • 我试过了,但它给了ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :members in model User
      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 2011-08-12
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多