Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Dave Faliskie
17,793 Pointssorting by forum topics
Im using ruby to make a forum. I have it set up so that each post has a topic. I was wondering how you can sort by the topic using buttons. Basically I want it to be like the treehouse forum where there is a list of topics and then a user can click a button and they will only see posts from that topic?
Im using Ruby so would this be the show file? my posts are called Discussions so I tried sorting the show with:
Discussion.where("topic = ?", @topic)
this seems to work but how do I set the variable @topic with different buttons.
Any help would be awesome.
1 Answer
Geoff Parsons
11,679 PointsThe simplest way would probably just be to pass the topic's ID in via a link_to:
<% for topic in @topics do %>
<%= link_to topic.name, discussions_path(topic_id: topic.id), class: "button" %>
<% end %>
And then in your controller action you'd want to find by topic_id (assuming Discussion belongs_to topic):
@discussions = Discussion.where(topic_id: params[:topic_id])
Dave Faliskie
17,793 PointsDave Faliskie
17,793 PointsI have it set up so that the topic is a column in the discussions table. Should I make the topics a table of their own?
Geoff Parsons
11,679 PointsGeoff Parsons
11,679 PointsAh, i apologize for the misunderstanding.
There's arguments for and against normalizing to that level. You can always extract it into its own table later via a migration.
If topic is just a string then you can pass it along in much the same way as i mentioned above:
<%= link_to topic.name, discussions_path(topic: topic), class: "button" %>@discussions = Discussion.where(topic: params[:topic])You may also want to look into setting up a custom route with a bound parameter. As it stands this will send topic via a GET parameter in the URL (e.g.
/discussions?topic=ruby). A custom route may look nicer and make it less obvious how things work on the inside (e.g./discussions/ruby).Dave Faliskie
17,793 PointsDave Faliskie
17,793 PointsThank you, Works perfectly!