简体   繁体   中英

Parsing multiple IDs from a URL in Rails

I'm building a sort-of Twitter clone, with (amongst others), models and Hashtag and Post, which have a has_many: through: relationship with each other.

Currently, visiting /hashtags/pizza will take you to a page that shows all posts with hashtag the hashtag #pizza . I want to add functionality so you can pass multiple hashtags in a URL and see the posts which contain all of those hashtags. For example, if you visited /hashtags/pizza/pasta (or hashtags/?pizza&pasta' or whatever's easiest to implement) you'd be shown a page containing all Posts which have BOTH the hashtag #pizza and the hashtag #pasta .

How would I do this? I have no idea where to begin.

For the record, my imagined code in the controller would be something like this. Feel free to poke holes in it:

1  def show
2    requested_hashtags = ??????? # an array of hashtags e.g. ["music", "guitar"]
3    hashtag1 = Hashtag.find_by_name(requested_hashtags[0]) # in this case r_h[0] = music
4    hashtag2 = Hashtag.find_by_name(requested_hashtags[1]) # and r_h[1] = guitar
5    @posts = hashtag1.posts & hashtag2.posts
6  end

Then in my view I'd just iterate over @posts . (The above example is dumbed down in that it assumes there's always exactly two hashtags requested but the principle is the same.)

So my question is, how do I complete line 2 of the code snippet above?

You can treat the url like any other string, so you could create a url like:

hashtags/?tags=pizza,pasta

And then in your controller (line 2):

requested_hashtags = params[:tags].split(",")

Another more commonly used approach in Rails is:

hashtags/?tags[]=pizza&tags[]=pasta

and then in your controller:

 requested_hashtags = params[:tags]

This second way is a pretty standard Rails convention.

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