2015-03-02 86 views
0

可以說我有這些模型:過濾多態性belongs_to的關係

class Image < ActiveRecord::Base 
    has_many :attachments, as: :attachable 
end 

class File < ActiveRecord::Base 
    has_many :attachments, as: :attachable 
end 

class Attachment < ActiveRecord::Base 
    belongs_to :attachable, polymorphic: true 

    # How can I add an image relation? 
    belongs_to :image ... 
    belongs_to :file ... 
end 

什麼是添加圖像/文件關係到附件模型

的最佳途徑,這就是我想要達到最終什麼:

class Page < ActiveRecord::Base 
    has_many :attachments, as: :attacher 

    # ? 
    has_many :images, 
    has_many :files 
end 

回答

0

也許類似於這個如果我的Imagelink =您的附件,我的圖片=您的頁面,我的項目=您的圖片,我的情景=您的文件(或它已經很長了,我不記得我自己的代碼正確)。

class Project 
    has_many :imagelinks, :as => :displayable, :dependent => :destroy 
    has_many :images, :through => :imagelinks 
end 

class Scenario 
    has_many :imagelinks, :as => :displayable, :dependent => :destroy 
    has_many :images, :through => :imagelinks 
end 

class Unittest 
    has_many :imagelinks, :as => :displayable, :dependent => :destroy 
    has_many :images, :through => :imagelinks 
end 

class Imagelink 
    # attributes: id, image_id, displayable_id, displayable_type 
    belongs_to :image 
    belongs_to :displayable, :polymorphic => true 
    belongs_to :project, :class_name => 'Project', :foreign_key => 'displayable_id' 
    belongs_to :scenario, :class_name => 'Scenario', :foreign_key => 'displayable_id' 
    belongs_to :unites, :class_name => 'Unittest', :foreign_key => 'displayable_id' 
end 

class Image 
    has_many :imagelinks, :dependent => :destroy 
    has_many :projects, :through => :imagelinks, :source => :project, :conditions => "imagelinks.displayable_type = 'Project'" 
    has_many :scenarios, :through => :imagelinks, :source => :scenario, :conditions => "imagelinks.displayable_type = 'Scenario'" 
    has_many :unittests, :through => :imagelinks, :source => :unittest, :conditions => "imagelinks.displayable_type = 'Unittest'" 
    has_attached_file :asset, :styles => { blah blah blah } 
end