I am little bit stuck with the following problem. I have two models:
class Book < ActiveRecord:Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord:Base
has_and_belongs_to_many :books
end
I have a list of specific tags that can but must not be used in the tags table:
tag1, tag2, tag3, tag4, tag5, …
Each new book can have several tags. As usual, relationships are stored in a join table “books_tags”.
How can I get a list of all tags that are at least related to one book?
You can use
:joinsas an option in your find call. E.g.This will only find tags that have a book associated and the
:select => 'distinct tags.*'ensures you only retrieve each tag once even if they are associated with multiple books.