Filtering results through URL (e.g. new?forum_id=3)

1 view
Skip to first unread message

Bob Sanders

unread,
Jul 20, 2008, 2:03:44 AM7/20/08
to rubyonra...@googlegroups.com
Is there a special code you have to place in the routes so filtering
results through the URL works?

For example, Ruby Forum does it with:

http://www.ruby-forum.com/topic/new?forum_id=3
http://www.ruby-forum.com/topic/new?forum_id=5
http://www.ruby-forum.com/topic/new?forum_id=7
etc.

Any ideas?
--
Posted via http://www.ruby-forum.com/.

gsterndale

unread,
Jul 20, 2008, 5:08:02 AM7/20/08
to Ruby on Rails: Talk
Hi Bob,

It seems that the example you gave may be doing something different
that what you describe. I believe the forum_id will be used as a value
in a new topic form, not as a "filter" for a list of topics.

You might look at this: http://api.rubyonrails.org/classes/ActionController/Resources.html#M000696
Specifically the part about routing association.

If you wanted to "filter" a list of topics by forum_id you might do
something like the following:
# routes.rb
map.resources :forums do |forums|
forums.resources :topics
end

This would generate routes like forum_topics and new_forum_topic so
you could call the following in your controllers & views:
# some_view.html.erb
<%= link_to "click here to see #{@my_forum.name} topics",
forum_topics_path(@my_forum) %>

This would result in a link to /forums/7/topics where @my_forum's id
is 7.

For a complete list of routes you've defined try this in your command
line:
$ rake routes

When GETing the path above, your topics_controller index action will
be called. In that method you'll need to look for params[:forum_id]
when finding your list of topics for the desired forum:
# topics_controller
def index
if params[:forum_id]
#find topics belonging to a specified forum
@forum = Forum.find(params[:forum_id])
@topics = @forum.topics
else
# find all topics
@topics = Topic.find(:all)
end
...
end

Good luck.

*untested code examples

On Jul 20, 2:03 am, Bob Sanders <rails-mailing-l...@andreas-s.net>
wrote:
> Is there a special code you have to place in the routes so filtering
> results through the URL works?
>
> For example, Ruby Forum does it with:
>
> http://www.ruby-forum.com/topic/new?forum_id=3http://www.ruby-forum.com/topic/new?forum_id=5http://www.ruby-forum.com/topic/new?forum_id=7

Bob Sanders

unread,
Jul 20, 2008, 6:43:54 AM7/20/08
to rubyonra...@googlegroups.com
Really appreciate the help, gsterndale! =)

Very detailed. Thank you so much!

Reply all
Reply to author
Forward
0 new messages