【发布时间】:2020-03-16 19:10:01
【问题描述】:
我正在尝试重新构建我的一些模型以包含多态关联,但我遇到了很多障碍。
即使像Tag.images << @crop_image 这样简单的东西也会返回错误:
ActiveModel::UnknownAttributeError - unknown attribute 'tag_id' for ImageTag.
我需要对collection<< 方法进行修改,以便它正确使用与多态关联一起使用的:taggable_id 和:taggable_type 列吗?
或者我在尝试设置模型时是否存在错误? Rails 5 Way 谈到在模型中指定 source 和 source_type 选项,我已经尝试在此处实施这些建议。
image.rb
has_many :image_tags
has_many :tags, through: :image_tags, source: taggable, source_type: 'Tag'
image_tag.rb
belongs_to :image
belongs_to :taggable, polymorphic: true
def build_taggable(params)
self.taggable = taggable_type.constantize.new(params)
end
tag.rb
has_many :image_tags
has_many :images, through: :image_tags, source: :taggable, source_type: 'Image'
【问题讨论】:
标签: ruby-on-rails collections has-many-through polymorphic-associations