Rails complex has_many and has_many through

拟墨画扇 提交于 2019-12-12 06:12:00

问题


I have 4 models: Drawer, Folder, FolderDocument and Document as follows:

class Drawer < ActiveRecord::Base
  has_many :folders #Drawer has many folders
end

class Folder < ActiveRecord::Base
  belongs_to :drawer
  has_many :folder_documents

  # Folder has a "version" attribute which reflects the latest version
  # Use proc to give back latest version by default e.g. folder.documents or folder.documents(5) will give back a specific version.      
  has_many :documents, :through => :folder_documents, :conditions => proc { |v = nil|
         v ||= self.version
         "documents.active IS TRUE AND version = #{v}"
       }, :uniq => true 
end

class FolderDocument < ActiveRecord::Base
  # Has a version attribute
  belongs_to :document
  belongs_to :folder
end

class Document < ActiveRecord::Base
  has_many :folder_documents
  has_many :folders, :through => :folder_documents
end

My problem is that I cant create a

has_many :documents, :through => :folders

on class Drawer as the proc conditions (for documents from FolderDocument) cant be calculated as "version" is calculated in context of Drawer not the intermediate folder association.

Is there way I can do this without creating another model between Folder and FolderDocuments called FolderVersion?

EDIT: Objective is to get all documents that belong to a folder for the current version (version in folders).

来源:https://stackoverflow.com/questions/14989680/rails-complex-has-many-and-has-many-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!