【问题标题】:Why is the source_type for this polymorphic association always 0?为什么这个多态关联的 source_type 总是 0?
【发布时间】:2014-03-30 20:14:54
【问题描述】:

由于某种原因,尽管设置了 :source_type,但多态 has_many :through 关联的源类型始终为 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

标记项目:

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 一无所获。

【问题讨论】:

  • 我创建了一个带有测试 here 的 rails 4 示例。检查tagged_item_test.rb。我的测试通过了。那些测试对你来说应该失败了?
  • 是的,失败了,但我发现了我的问题。基本上我是个白痴。我把 taggable_type 字段作为一个整数。哇!
  • hobberwickey 如果您认为我的示例项目帮助您解决了您的问题,请支持我的回答:)

标签: ruby-on-rails ruby-on-rails-4 has-many-through polymorphic-associations


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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:由于我对这个问题进行了一些研究,我不妨发布答案以防有人从中受益...... :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 2011-12-28
      相关资源
      最近更新 更多