开发者

Rails 3: Check for routing error in rails code

I have a lot of courses in my website. I have a "go to course" form. When user inputs a valid course name, I successfully redirect that user to that course page.

 def courses
    @title = "Courses"
    @path  = "#{root_path}"+"course/" + "#{params[:course]}"
    if @path == "/course/"
        @title = "Courses"
        render 'courses'
    else 
        redirect_to @path
    end
end

This works for all valid inputs that is if the route exists. I want to take care of the error case when the user inputs invalid course name which would cause an invalid route. I want to check for routing error开发者_如何学Go in the code and let the user know with an error message. Is this possible?"


Instead of building out custom routes in your controller, use Rails convention and place them in config/routes.rb:

    resources :courses

This creates the route /courses/:id for you. Then your controller would simplify to:

    def show
      @title = "Courses"
    end

It would help if you included your model, controller and routes.rb.


You can use this to check if your route is valid:

def check_route(route)

    @route_valid = true
    begin
        ActionController::Routing::Routes.recognize_path(@route, :method => :get)
    rescue
        # error means that your route is not valid, so do something to remember that here
        @route_valid = false
    end
end

But in general, I do not like your idea of creating a route based on a course. Why not just use a simple finder?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜