【问题标题】:In Rails, how would you merge these two different has_manys into one?在 Rails 中,如何将这两个不同的 has_many 合并为一个?
【发布时间】:2013-07-04 10:08:07
【问题描述】:

假设我们有一个用户。

一个用户通过这样的帐户拥有_many 个文档……

class User < ActiveRecord::Base
  belongs_to :account
  has_many :documents, :through => :account, :order => "created_at DESC"
end

class Account < ActiveRecord::Base
  has_one :owner, :class_name => "User", :dependent => :destroy
  has_many :documents, :dependent => :destroy
end

class Document < ActiveRecord::Base
  belongs_to :account
end

又好又简单,这就是它变得棘手的地方……

用户还可以在文档上进行协作,这通过协作者连接表...

class Collaborator < ActiveRecord::Base
  belongs_to :user
  belongs_to :documnet
end

class Document < ActiveRecord::Base
  has_many :collaborators, :dependent => :destroy
  has_many :users, :through => :collaborators
  accepts_nested_attributes_for :collaborators, :allow_destroy => true
end

这是我不确定的最终用户位。我想添加另一个有很多文档,当您调用 user.documents 时,它会通过他们的帐户和他们正在协作的文档混合这两个文档......

class User < ActiveRecord::Base
  belongs_to :account
  has_many :documents, :through => :account, :order => "created_at DESC"

  #documents need to do both has manys…
  has_many :collaborators, :dependent => :destroy
  has_many :documents, :through => :collaborators
end

谢谢,有点长,但我能想到一个巧妙的解决方案。任何帮助将非常感激。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord has-many-through has-many


    【解决方案1】:

    您可以创建一个方法来请求表documentsaccountscollaborators 以查找与用户相关的文档:

    class User < ActiveRecord::Base
    
      #...
    
      def documents
        Document.includes(:account, :collaborators).where('collaborators.user_id = ? OR documents.account_id = ?', self.id, self.account.id)
      end
    
    end
    

    我没有测试过这个请求,但我希望你能明白。如有错误请指正。

    对于2个has_many documents, :through...,如果你不再需要它们,你可以删除它们;否则,你必须给它们起不同的名字(和上面的方法不同)。

    【讨论】:

    • 谢谢!我对其进行了一些修改以使其正常工作,添加我的更改。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多