My application is composed of Category
that has_many products
. Category as well as products have a publication date.
The show page of category display the product from that category.
The show and index actions of Category_controller are very simple (published is a scope):
def index
@categories = Category.published
end
def show
@categories = Category.find(params[:id])
unless @categories.datepublication <= Time.now
redirect_to categories_path
end
end
As you can see it display published category and redirect you to category index when you are being too curious for your own sake.
Now it would be great to display only published products in the show view of a category. I do not know how to do that except with a if in the view, but it seems to me that filtering elements is not the job of the view. What is the correct MVC way of filtering a nested element ?
You can chain scopes, even through associations. From your example I gather that your categories have a publication date but your products also have their own publication date, is that right?
In that case you could set up a scope on your products similar to the one you have on your categories and just use it the same way, i.e.:
@products = @category.products.published
Then whether you want to preload the @products instance variable in the controller or just use @category.products.published in the view is up to you. If the application is simple enough I usually just use the scoped query in the view myself.