在轨道中具有Ploymorphic关联的STI

时间:2016-01-16 06:26:38

标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations single-table-inheritance

我的模型名为Slider

class Slider < ActiveRecord::Base

end
与滑块

具有单表继承关系的

HomeBannerSlider

class HomeBannerSlider < Slider

    has_many :images, as: :imageable
    accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy: true

end
给出

Image模型

class Image < ActiveRecord::Base
   belongs_to :imageable, polymorphic: true
   has_attached_file :image
end

我的问题是每当我使用以下命令保存HomeBannerSlider

      @admin_home_banner_slider = HomeBannerSlider.new(admin_home_banner_slider_params)

     @admin_home_banner_slider.save

它将imageable_type模型中的Image保存为Slider

@admin_home_banner_slider.images
<Image:0x007f5e6ef7af20
  id: nil,
  imageable_id: nil,
  imageable_type: "Slider",
  title: "2",
  description: "2",
  link_button: nil,
  link_button_title: nil,
  owner: nil,
  publish: nil,
  priority: nil,
  created_at: nil,
  updated_at: nil,
  image_file_name: nil,
  image_content_type: nil,
  image_file_size: nil,
  image_updated_at: nil>]

但我希望它将imageable_type存储为HomeBannerSlider

3 个答案:

答案 0 :(得分:0)

尝试在Image模型中添加此内容:

before_validation :set_type

def set_type
  self.imageable_type = imageable.class.name
end

答案 1 :(得分:0)

您可以将模型中的imageable_type覆盖为

def imageable_type=(imageType)
  super(imageType.classify.constantize.base_class.to_s)
end

答案 2 :(得分:0)

来自activerecord文档 - http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations - &#34;将多态关联与单表继承(STI)结合使用有点棘手。为了使关联按预期工作,请确保将STI模型的基本模型存储在多态关联的类型列中#34;。

因此rails特别想要存储在那里的基类型,如果你访问my_image.imageable它仍会加载正确的类型,因为它在创建该对象时使用Slider表中的类型,而且对于整个Slider表是唯一的,而不是只是在表中的每种类型。

总而言之,有一个宝石可以添加您想要的行为 - https://github.com/appfolio/store_base_sti_class