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"
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').