【问题标题】:STI with Ploymorphic association in railsSTI 与 Rails 中的多态关联
【发布时间】:2016-01-16 06:26:38
【问题描述】:

我的模型名为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_typeImage模型中保存为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

【问题讨论】:

  • 滑块表中有类型列吗?
  • 是的@TomWalpole ,并且在type 列中它正确存储HomeBannerSlider,但在每个图像实例中它都将Slider 存储在imageable_type 列中

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


【解决方案1】:

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

所以 rails 特别希望将基本类型存储在那里,如果您访问 my_image.imageable,它仍然会加载正确的类型,因为它在创建对象时使用 Slider 表中的类型,并且 id 对于整个 Slider 表是唯一的,而不是就在表中的每种类型中。

话虽如此,有一个 gem 可以将你想要的行为添加到 rails - https://github.com/appfolio/store_base_sti_class

【讨论】:

    【解决方案2】:

    尝试将其添加到您的 Image 模型中:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-12-16
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多