簡體   English   中英

關注的Polymorphic關聯的Rails逆給出TypeError:不能轉換Class

[英]Rails inverse of Polymorphic association in concern gives TypeError: can't cast Class

我正在嘗試使用本教程中的信息來了解多態關聯的問題。 我有以下內容:

關注/ taggable.rb:

module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, :as => :taggable
    has_many :tags, :through => :taggings
  end

  def tag_list
    tags.map(&:name).join(', ')
  end

  def tag_list=(names)
    self.tags = names.split(',').map do |name|
      Tag.where(name: name.strip).first_or_create!
    end
  end

  module ClassMethods
    def tag_counts
      Tag.select('tags.*, count(taggings.tag_id) as count').joins(:taggings).group('taggings.tag_id')
    end
  end
end

車型/ article.rb:

class Article < ApplicationRecord
  include Taggable

  def self.tagged_with(name)
    Tag.find_by!(name: name).articles
  end

end

車型/ tagging.rb:

class Tagging < ApplicationRecord

  belongs_to :tag
  belongs_to :taggable, :polymorphic => true

end

車型/ tag.rb:

class Tag < ApplicationRecord
  has_many :taggings
  has_many :articles, through: :taggings, source: :taggable, source_type: Article

end

前進協會工作得很好。 我可以問:

Article.first.tags
#=> Article Load (0.2ms)  SELECT  "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT ?  [["LIMIT", 1]]
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? LIMIT ?  [["taggable_id", 1], ["taggable_type", "Article"], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Tag id: 1, name: "Superhero", created_at: "2017-11-12 21:06:33", updated_at: "2017-11-12 21:06:33">, #<Tag id: 2, name: "Bat", created_at: "2017-11-12 21:06:33"...

但如果我這樣做:

Tag.first.articles
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT ?  [["LIMIT", 1]]
TypeError: can't cast Class

我已經嘗試了tag.rb模型中的關聯的幾個變體,但似乎找不到任何有效的。

標簽中的source_type has_many:通過關聯需要是一個字符串:

has_many :articles, through: :taggings, source: :taggable, source_type: "Article"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM