8

由于某些原因,多态性has_many :through关联的源类型始终为0,尽管设置了:source_type为什么这个多态关联的source_type总是0?

这里是我的模型看起来像...

富:

has_many :tagged_items, :as => :taggable 
has_many :tags, :through => :tagged_items 

酒吧:

has_many :tagged_items, :as => :taggable 
has_many :tags, :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, :through => :tagged_items, :source => :taggable, :source_type => "Bar" 

尽可能靠近我可以告诉大家,这是一个完全正常的设置,我可以创建/添加标签,但taggable_type总是最终被0

任何想法是为什么? Google一无所获。

+0

我创建了一个轨道与测试[这里](4例如HTTPS ://github.com/raviolicode/has_many_polymorphic_example)。检查[tagged_item_test.rb](https://github.com/raviolicode/has_many_polymorphic_example/blob/master/test/models/tagged_item_test.rb)。我的测试通过。那些测试应该会失败吗? – raviolicode

+0

是的失败了,但我找出了我的问题。基本上我是个白痴。我把taggable_type字段作为整数。卫生署! – hobberwickey

+0

hobberwickey请upvote我的答案,如果你认为我的示例项目帮助你解决你的问题:) – raviolicode

回答

4

我自己想出了这个,只是回答,因为我确定我不是第一个也不是最后一个犯这个愚蠢错误的人(事实上我可能以前做过)。我将taggable_type字段的列类型作为整数而不是字符串。

你会认为这可能会导致错误,但它不会。它只是不起作用。

5

找到一个在问题中对模型进行测试的工作示例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:由于我没有在这个问题上的一些研究,我还不如后万一有人回答可以从中受益...... :)