[英]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. 我正在建立一个Twitter克隆,以及其他模型,模型和Hashtag和Post,它们之间具有
has_many: through:
关系。
Currently, visiting /hashtags/pizza
will take you to a page that shows all posts with hashtag the hashtag #pizza . 目前,访问
/hashtags/pizza
会将您带到一个页面,该页面显示所有带有#标签的主题#tagzza 。 I want to add functionality so you can pass multiple hashtags in a URL and see the posts which contain all of those hashtags. 我想添加功能,以便您可以在URL中传递多个标签,并查看包含所有这些标签的帖子。 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 . 例如,如果您访问了
/hashtags/pizza/pasta
(或hashtags/?pizza&pasta'
或最容易实现的东西),则会看到一个页面,其中包含所有具有#pizza标签和#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
. 然后在我看来,我只是遍历
@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? 所以我的问题是,我怎么完成上面的代码段的第2行?
You can treat the url like any other string, so you could create a url like: 您可以像对待其他任何字符串一样对待该url,因此您可以像这样创建一个url:
hashtags/?tags=pizza,pasta
And then in your controller (line 2): 然后在您的控制器中(第2行):
requested_hashtags = params[:tags].split(",")
Another more commonly used approach in Rails is: Rails中另一个更常用的方法是:
hashtags/?tags[]=pizza&tags[]=pasta
and then in your controller: 然后在您的控制器中:
requested_hashtags = params[:tags]
This second way is a pretty standard Rails convention. 第二种方法是相当标准的Rails约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.