微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 为什么这个多态关联的source_type总是为0?

由于某种原因,多态性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:由于我对这个问题进行了一些研究,我不妨发布答案,万一有人可以从中受益……

原文地址:https://www.jb51.cc/ruby/270132.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐