为什么此多态关联的source_type始终为0?

hob*_*key 8 ruby-on-rails has-many-through polymorphic-associations ruby-on-rails-4

由于某种原因,多态has_many :through关联的源类型始终为0,尽管设置了a :source_type.

这就是我的模特的样子......

富:

has_many :tagged_items, :as => :taggable
has_many :tags, :through => :tagged_items
Run Code Online (Sandbox Code Playgroud)

酒吧:

has_many :tagged_items, :as => :taggable
has_many :tags, :through => :tagged_items
Run Code Online (Sandbox Code Playgroud)

TaggedItem:

belongs_to :tag
belongs_to :taggable, :polymorphic => true
Run Code Online (Sandbox Code Playgroud)

标签:

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"
Run Code Online (Sandbox Code Playgroud)

尽可能接近我可以说这是一个非常精细的设置,我能够创建/添加标签,但taggable_type总是最终为0.

任何想法都是为什么?谷歌一无所获.

hob*_*key 5

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

您会认为这可能会导致错误,但事实并非如此。它只是不起作用。


rav*_*ode 5

这里可以找到问题模型测试的工作示例.

它不能解决问题的原因是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
Run Code Online (Sandbox Code Playgroud)

请注意,t.references :taggable, polymorphic:true将生成两列schema.rb:

t.integer  "taggable_id"
t.string   "taggable_type"
Run Code Online (Sandbox Code Playgroud)

因此,对于问题和迁移中的相同模型,以下测试通过:

 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
Run Code Online (Sandbox Code Playgroud)

注:Rails 3中有有关活动的问题has_many :through和多态关联,如图所示这里.虽然,在Rails 4中,这已经解决了.

PS:由于我对这个问题进行了一些研究,我不妨发布答案,万一有人可以从中受益...... :)