【问题标题】:Double join with habtm in ActiveRecord在 ActiveRecord 中与 habtm 双重加入
【发布时间】:2009-07-29 23:15:54
【问题描述】:

我有一个奇怪的情况,需要双内连接。我已经尝试了我需要的查询,我只是不知道如何让 rails 做到这一点。

数据

  • 帐户(has_many :sites)
  • 网站(habtm :users,belongs_to :account)
  • 用户(habtm :sites)

忽略它们是 habtm 或其他什么,我可以使它们成为 habtm 或 has_many :through。

我希望能够做到

@user.accounts

@account.users

那我当然应该可以了

@user.accounts < @some_other_account

然后让@user.sites 包含来自@some_other_account 的所有网站。

我已经摆弄了 habtm 和 has_many :through 但无法让它做我想做的事。

基本上我需要得到这样的查询(从 phpmyadmin 复制。经过测试并且有效):

SELECT accounts.* 
FROM accounts
INNER JOIN sites ON sites.account_id = accounts.id
INNER JOIN user_sites ON sites.id = user_sites.site_id
WHERE user_sites.user_id = 2

我可以这样做吗?进行这种双重连接是个好主意吗?我假设如果用户一开始就与帐户建立关联,然后担心得到@user.sites,它会更好地工作,但如果保持原样(用户网站)。

【问题讨论】:

    标签: ruby-on-rails activerecord associations has-and-belongs-to-many


    【解决方案1】:

    我认为最好为此创建自定义方法,而不是将其硬塞进一个关联中。例如。

    # in user.rb
    def accounts
      Account.all(:include => {:sites => :users}, :conditions => ["users.id=?", self])
    end
    
    def add_account(other_account)
      other_account.sites.each do |site|
        self.sites << site
      end
    end
    
    # in account.rb
    def users
      User.all(:include => {:sites => :account}, :conditions => ["accounts.id=?", self])
    end
    

    未经测试,但这应该适用于 HABTM 或 has_many :through 关联。根据您采用的方法,您可以对查询进行一些优化。

    有一天我们可能会获得对深度嵌套的has_many :through 的支持,它可以处理其中的一些问题。

    【讨论】:

    • 谢谢!顺便说一句,喜欢截屏视频。
    【解决方案2】:

    这可能对您有用(Rails 2.x)

    http://github.com/ianwhite/nested_has_many_through

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多