olimart
olimart

Reputation: 1569

Dynamic routes in rails with condition

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

Answers (2)

olimart
olimart

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

roo
roo

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

Related Questions