【问题标题】:Filtering polymorphic belongs_to relations过滤多态belongs_to关系
【发布时间】:2015-03-02 21:19:22
【问题描述】:

假设我有这些模型:

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

【问题讨论】:

    标签: ruby-on-rails activerecord polymorphism


    【解决方案1】:

    如果我的图片链接 = 你的附件,我的图片 = 你的页面,我的项目 = 你的图片,我的场景 = 你的文件(或者它已经太久了,我不记得我自己的代码正确),也许类似于此。

    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
    

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多