Should my URL’s in Rails look like:
http://foobar.com/articles?category=recent
– OR –
http://foobar.com/articles/recent
I find the former to be more RESTFUL, but the latter to be more cleaner (code-wise). For example, the code can look like:
In Article controller:
def index
if params[:category] == 'recent'
@articles = Article.by_recent
elsif params[:category] == 'expired'
@articles = Article.by_expired
end
end
In Article, index view:
<% unless @articles.blank? %>
<ul>
<% @articles.each do |article| %>
<li><%= article.title %></li>
<li><%= article.content %></li>
<% end %>
</ul>
<% end %>
With http://foobar.com/articles/recent, I would have to customize my routes. Something like:
match 'articles/:category' => 'articles#index'
Above will access the Article controller, index action. Or even:
resources :articles do
collection do
get 'recent'
end
end
Which will allow for urls like http://foobar.com/articles/recent, but needs a ‘recent’ action in the Article controller.
Both seem pretty useful, in the end of the day. But which is the general consensus? Using the query string approach (http://foobar.com/articles?category=recent) or the other way (http://foobar.com/articles/recent).
Looking forward to your suggestions.
Obviously like you said you could go either way, but since something like “recent” is a condition of or query against articles I would go with the former. If it were a nested attribute and its own model the second approach is arguably better, but since it isnt you really lose a lot of flexibility to change and refactor the approach down the road.
For instance if you wanted to do “old” as opposed to “recent” you would not be able to simply pass in an “old” parameter, but would have to hardcode that with its own action and views in the same controller as “recent” which is of course a lot more work for nothing.