[英]Rails inverse of Polymorphic association in concern gives TypeError: can't cast Class
I am trying to use the information in this tutorial to learn concerns with polymorphic associations. 我正在尝试使用本教程中的信息来了解多态关联的问题。 I have the following: 我有以下内容:
concerns/taggable.rb: 关注/ 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
models/article.rb: 车型/ article.rb:
class Article < ApplicationRecord
include Taggable
def self.tagged_with(name)
Tag.find_by!(name: name).articles
end
end
models/tagging.rb: 车型/ tagging.rb:
class Tagging < ApplicationRecord
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end
models/tag.rb: 车型/ tag.rb:
class Tag < ApplicationRecord
has_many :taggings
has_many :articles, through: :taggings, source: :taggable, source_type: Article
end
The forward associations work just fine. 前进协会工作得很好。 I can ask: 我可以问:
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"...
But if I do: 但如果我这样做:
Tag.first.articles
Tag Load (0.3ms) SELECT "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT ? [["LIMIT", 1]]
TypeError: can't cast Class
I've tried several variations on the associations in the tag.rb
model but can't seem to find any that works. 我已经尝试了tag.rb
模型中的关联的几个变体,但似乎找不到任何有效的。
标签中的source_type has_many:通过关联需要是一个字符串:
has_many :articles, through: :taggings, source: :taggable, source_type: "Article"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.