代码之家  ›  专栏  ›  技术社区  ›  Brian Kelly

如何将特定于父实例的信息添加到多个关系中?

  •  0
  • Brian Kelly  · 技术社区  · 15 年前

    我正在使用 作为类固醇的标签

    • 类别
    • 入口- 并使用单表继承包含以下内容
      • 故事
      • 话题

    类别有两个重要字段:

    • 标记:字符串-与此类别关联的标记列表
    • primary_tag:string-分配给为类别创建的任何主题的单个标记

    • 类别的“故事”页面列出了使用该类别的标记标记的所有故事。
    • 类别的“主题”页面列出了使用该类别的标记标记的所有主题和故事。

    故事和主题的创建如下所示:

    • 当用户创建主题时,它是在类别的上下文中创建的。它在创建时会自动标记为类别的主_标记。

    我试图为类别定义3有很多关系,它使用标记查找相关条目、故事和主题。如果我在控制器代码中执行此操作,我将使用以下命令:

    @category = Category.find(1)
    @entries = Entry.find_tagged_with(@category.tags) # All Entries
    @entries = Story.find_tagged_with(@category.tags) # Just Stories
    @entries = Topic.find_tagged_with(@category.tags) # Just Topics
    

    我想将其作为Category的实例方法,以便按如下方式调用它:

    @category.find(1)
    @entries = @category.entries # All Entries
    @entries = @category.stories # Just Stories
    @entries = @category.topics  # Just Topics
    

    我不知道在:has\u many声明中如何/指定什么来指定上面的类方法,以使用所讨论的category实例执行工作。

    has_many :entries do
      def tagged
        Entry.find_tagged_with(self.tags)
      end
    end
    

    但最终会出现以下错误:

    >> @category = Category.find(2)
    => #<Category id: 2, title: "Comics", description: "Comics", enabled: true, tags: "comics", created_at: "2009-06-22 13:29:52", updated_at: "2009-07-01 13:44:09", parent_id: nil, image: "", important: true, stories_enabled: true, topics_enabled: true, primary_tag: "comics">
    >> @category.entries.tagged
    NoMethodError: undefined method `tags' for #<Class:0x22781dc>
    

    我尝试过this.tags和reflection.tags,但是它们都抱怨一个未定义的方法,所以对于这个方法的范围,我确实不了解一些东西。

    1 回复  |  直到 15 年前
        1
  •  1
  •   user135071 user135071    15 年前

    我想你想用 代理所有人 自己 .

    试试这个:

    has_many :entries do
      def tagged
        Entry.find_tagged_with(proxy_owner.tags)
      end
    end
    

    here .