Rails模型命名空间class_name选择

时间:2016-02-24 00:10:29

标签: ruby-on-rails

我有这些模型:Post Tag Post::Tag

Tag是标记信息模型。 Post::Tag链接模型。

Post模型中,我设置了:

  has_many :post_tag, class_name: 'Post::Tag'
  has_many :tags, class_name: 'Tag', through: :post_tag, source: :tag, dependent: :destroy

这是Post::Tag型号:

class Post::Tag < ActiveRecord::Base
  belongs_to :post, class_name: 'post', foreign_key: :video_id
  belongs_to :tag, class_name: 'Tag', foreign_key: :tag_id, counter_cache: :posts_count
end

我的问题是post.tags.take.tag.classPost::Tag,但我实际上想要Tag,如何修复?

1 个答案:

答案 0 :(得分:1)

您可能需要考虑不同的命名架构以避免这种混淆。特别是因为表到常量查找是非常复杂的。

这是一种多态设置,其中标记可以应用于任何类型的资源:

class Tag
  has_many :taggings
  has_many :tagged_items, 
     through: :taggings,
     source: :resource
end

# - tag_id [Int
# - resource_id [Int]
# - resource_type [String]
class Tagging
  belongs_to :tags
  belongs_to :resource, polymorphic: true
end

class Post
  has_many :taggings, as: :resource
  has_many :tags, through: :taggings
end 

如果您不需要多态,您可以将其声明为:

class Tag
  has_many :taggings
  has_many :posts, through: :taggings
end

# - tag_id [Int
# - resource_id [Int]
# - resource_type [String]
class Tagging
  belongs_to :tags
  belongs_to :post
end

class Post
  has_many :taggings
  has_many :tags, through: :taggings
end