ruby-on-rails – 为什么这个多态关联的source_type总是为0?
发布时间:2020-12-16 19:08:59 所属栏目:百科 来源:网络整理
导读:由于某种原因,多态性has_many的源类型:通过关联始终为0,尽管设置了:source_type. 这就是我的模特的样子…… 富: has_many :tagged_items,:as = :taggablehas_many :tags,:through = :tagged_items 酒吧: has_many :tagged_items,:through = :tagged_item
由于某种原因,多态性has_many的源类型:通过关联始终为0,尽管设置了:source_type.
这就是我的模特的样子…… 富: has_many :tagged_items,:as => :taggable has_many :tags,:through => :tagged_items 酒吧: has_many :tagged_items,:through => :tagged_items TaggedItem: belongs_to :tag belongs_to :taggable,:polymorphic => true 标签: has_many :tagged_items has_many :foos,:through => :tagged_items,:source => :taggable,:source_type => "Foo" has_many :bars,:source_type => "Bar" 尽可能接近我可以说这是一个非常精细的设置,我能够创建/添加标签,但taggable_type总是最终为0. 任何想法都是为什么?谷歌一无所获. 解决方法
查找问题中模型测试的工作示例为
here.
它不能解决问题的原因是迁移db / migrate / [timestamp] _create_tagged_items应该像这样生成: class CreateTaggedItems < ActiveRecord::Migration def change create_table :tagged_items do |t| t.belongs_to :tag,index: true t.references :taggable,polymorphic: true t.timestamps end end end 注意t.references:taggable,polymorphic:true将在schema.rb上生成两列: t.integer "taggable_id" t.string "taggable_type" 因此,对于问题和迁移中的相同模型,以下测试通过: require 'test_helper' class TaggedItemTest < ActiveSupport::TestCase def setup @tag = tags(:one) end test "TaggedItems have a taggable_type for Foo" do foo = Foo.create(name: "my Foo") @tag.foos << foo assert TaggedItem.find(foo.id).taggable_type == "Foo" end test "TaggedItems have a taggable_type for Bar" do bar = Bar.create(name: "my Bar") @tag.bars << bar assert TaggedItem.find(bar.id).taggable_type == "Bar" end end 注意:Rails 3有关于has_many:through和多态关联的活动问题,如here所示.尽管如此,在Rails 4中,这已得到解决. PS:由于我对这个问题进行了一些研究,我不妨发布答案,万一有人可以从中受益…… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |