I have a model posts, which belongs_to category (which uses friendly_id). Now i want to list all Posts in an Category. To get the index page i want to use a link like: http://mysite/posts/category/_category_slug_, for that i made the following route:
match 'posts/category/:category/' => 'posts#index'
And in my post controller i got:
def index
if params[:category]
@posts = Post.all(:joins => :category, :conditions => {"categories.cached_slug" => params[:category]})
else
@posts = Post.all.reverse
end
...
It works like it should, but i dont t开发者_开发问答hink its the friedndly_id way to do it.
Is there a better way to achive this? thanks for your help.
FriendlyId adds the ability to do a find on a model using the slug, and is smart enough to check the cached_slug column first.
You can achieve the same result by performing a find on the Category model first then getting all the posts.
This assumes there is a has_many and belongs_to association in place with the referencing ID columns (or HABTM)
def index
if params[:category]
@posts = Category.find(params[:category]).posts
else
@posts = Post.all.reverse
end
...
Since you're passing in a category param (being friendly_id), it makes sense to reference it via the Category model.
-- more info added --
ALSO: Historical finds will still work .. So, if you have generated a new slug by renaming a category, the old url will behave correctly (great if you're avoiding 404's)
精彩评论