Search code examples
ruby-on-railsruby-on-rails-3tagsrailscastsvirtual-attribute

Rails 3: Railscast #167 virtual attribute for creating tags - @user.tags


I would like to a tagging system where I can separate the tags by the user's who created them. I followed Railscast #167 about setting up tags using virtual attributes, but that way only lets me call @post.tags to find the tags for a post, but I can't call @user.tags and find all their tags.

How could I augment this so that @user.posts.tag("music") would return all their posts with the tag music?

Thanks for an help or insight into what I'm doing wrong.


Solution

  • @user.posts returns an array, so you could filter this pretty easily with something like this:

    @user.posts.select do |post|
      post.tag_names.include? "music"
    end
    

    You might, however, run into an issue with the records not being eagerly loaded in that situation. Something like this should take care of that:

    Post.includes(:taggings => :tags).where("posts.user_id = ?", @user.id).select do |post|
      post.tag_names.include? "music"
    end