Reputation: 1569
I have a set of pages with public attribute. I want the routes file handle dynamic routes but only for public pages.
I currently have the following, but there is no restriction, all pages are visible. What I'd like is go to page only if page is public else raise 404.
Page.public.each do |page|
get "/:slug", controller: 'pages', action: 'show' if page.public?
end
Upvotes: 1
Views: 405
Reputation: 1569
The working code is (was missing 'Not Found')
class PagesController
before_filter :is_public, only => [:show]
protected
# Check if the page is public, otherwise raise a routing error.
def is_public
raise ActionController::RoutingError.new('Not Found') unless Page.find(params[:slug]).public?
end
end
Upvotes: 0
Reputation: 7196
I would put this behaviour in the controller rather than in routes.rb, since a page could change from private to public during runtime and routes in production are initialised only once at the start.
class PagesController
before_filter :is_public, only => [:show]
protected
# Check if the page is public, otherwise raise a routing error.
def is_public
raise ActionController::RoutingError.new unless Page.find(params[:slug]).public?
end
end
Upvotes: 2