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:由於我沒有在這個問題上的一些研究,我還不如後萬一有人回答可以從中受益...... :)