简体   繁体   中英

Hashtag filtering with Ruby on Rails

New Rails programmer here. There is probably a pretty simple solution to this, but I just can't figure it out. Here's the deal: lets say I have many posts on a single page. Each post has a content field, and some of those content fields contain #hashtags within the content.

I want to develop an algorithm that scans the content of every single post (say, every 2 seconds) and displays a list of every hashtag. I'm thinking AJAX will be necessary, because the posts feature AJAX edit-in-place. Thus, if a post is changed and a new hashtag is created, the hashtag list should be updated automatically to reflect this. Also, each hashtag on the hashtag list should be clickable, sending a search query and in turn displaying the posts that contain the selected hashtag.

This end result is similar to tagging and a tag cloud, but should be dynamic and integrated (as opposed to having a tag field for each post). I don't want to attach any tags to the posts as a database column. I just want the application to scan the content of every single post and display a clickable hashtag list.

All suggestions are greatly appreciated.

Personally, I would use jQuery to implement the AJAX functionality you need. Javascript will be used to check the server for new hashtags, and the actual hashtag searching will be done on the server. In your Post model, you could have something like this to do the actual searching:

class Post < ActiveRecord::Base
  # class methods
  class << self
    def hashtags
      tags = []

      # cycle through all posts that contain a hashtag, and add them to list
      Post.all(:conditions => 'body like "%#"').each do |post|
        tags += post.hashtags
      end

      # remove duplicates and sort alphabetically
      tags = tags.uniq.sort
    end
  end

  # instance methods
  def hashtags
    @hashtags ||= body.scan(/#\w+/)
  end
end

There are two methods here with the same name, but one is called on the class ( Post.hashtags ) to get all hashtags across all posts, and the second one is called on a single instance ( post.hashtags ) to get just the hashtags from that post.

There are several other pieces to the puzzle - your controller code, your views, and your javascript. This question is a tall order for a volunteer site. You're asking for several different things to be done for you.

My advice is to start building this as I've described, and ask for help on the pieces that you have trouble with along the way. We're more than happy to help, but you're asking for an entire javascript-driven MVC stack. Try to limit your questions to something that can be answered in 5-10 minutes, and you're likely to get a lot more feedback and help.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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