简体   繁体   English

如何基于模型的相关数据提取条目? (路轨)

[英]How to pull entries from a model based off their associated data? (Rails)

Let's suppose I have a Discussion model, and that a discussion can be tagged. 假设我有一个“讨论”模型,并且可以标记一个讨论。 These tags are associated to the discussion through a taggings table. 这些标签通过标签表与讨论相关联。

I want to define a method .tagged_with(tag) that will basically do: 我想定义一个方法.tagged_with(tag)基本上可以做到:

 def tagged_with

      Discussion.where(#something about tags include the tag given)
 end

I do have some methods that might be helpful already set up. 我确实有一些可能已经设置好的方法。 For example, I have tag_list 例如,我有tag_list

 def tag_list
     tags.map(&:name).joins(", ") #my tags are separated by commas, not spaces)
 end

And if someone knows an answer to the simpler question of trimming the Discussion model based off one tag, how can I expand it to be more adaptable - for example, accepting an argument of multiple tags, and being able to specify that any or all are necessary. 并且,如果有人知道一个简单的问题的答案,即基于一个标签修整“讨论”模型,那么我该如何扩展它以使其更具适应性-例如,接受多个标签的参数,并能够指定其中一个或全部为必要。 EG: 例如:

 Discussion.tagged_with(tag1, tag2, :any => true)

FYI some of the code from the associations: 仅供参考,来自关联的一些代码:

has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings, :source => :tag, :source_type => "Tag"

You should be able to join the tags table into your Discussion query, through its has_many relationship. 您应该能够通过其has_many关系将标签表加入“讨论”查询中。 Discussion.joins(:tags).where(:tags => {:name => array_of_tags}) . Discussion.joins(:tags).where(:tags => {:name => array_of_tags})

With the below method definition, you can do something like Discussion.tagged_with(['foo', 'bar']) or Discussion.tagged_with('foo') . 使用以下方法定义,您可以执行诸如Discussion.tagged_with(['foo', 'bar'])Discussion.tagged_with('foo')

def self.tagged_with(tag_or_tags)
  joins(:tags).where(:tags => {:name => tag_or_tags})
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM