如何根据相关数据从模型中提取条目? (导轨)
假设我有一个讨论模型,并且可以标记讨论。这些标签通过标签表与讨论相关联。
我想定义一个方法 .tagged_with(tag) ,它基本上可以做到:
def tagged_with
Discussion.where(#something about tags include the tag given)
end
我确实已经设置了一些可能有用的方法。例如,我有 tag_list
def tag_list
tags.map(&:name).joins(", ") #my tags are separated by commas, not spaces)
end
如果有人知道根据一个标签修剪讨论模型这一更简单问题的答案,我如何才能将其扩展为更具适应性 - 例如,接受多个标签的参数,并能够指定其中任何一个或全部是必需的。 EG:
Discussion.tagged_with(tag1, tag2, :any => true)
仅供参考,协会的一些代码:
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings, :source => :tag, :source_type => "Tag"
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:
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
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够通过其 has_many 关系将标签表连接到您的讨论查询中。
Discussion.joins(:tags).where(:tags => {:name => array_of_tags})
。通过以下方法定义,您可以执行诸如
Discussion.tagged_with(['foo', 'bar'])
或Discussion.tagged_with('foo')
之类的操作。You should be able to join the tags table into your Discussion query, through its has_many relationship.
Discussion.joins(:tags).where(:tags => {:name => array_of_tags})
.With the below method definition, you can do something like
Discussion.tagged_with(['foo', 'bar'])
orDiscussion.tagged_with('foo')
.