fifigyuri
fifigyuri

Reputation: 5899

Format dependent rails routes

How to realize the following routing in rails:

Obviously that's a use case for a single page application, where rails is mostly used only for serving jsons. Most of the pages are just very simple layouts with some values bootstrapped.

Thanks for hints.

Upvotes: 0

Views: 165

Answers (1)

AdamT
AdamT

Reputation: 6485

The way this problem is solved in Rails can be handled in the controller in a single action. In the routes file you would just declare the resource:

resources :posts

And the controller would look like this:

def index
  @posts = Post.all

  respond_to do |format|
    format.html  # index.html.erb
    format.json  { render :json => @posts }
  end
end

As you can see, the type of the response depends on the type requested.

However, if you really do want to route according to type I guess you could try something like this:

match 'posts/:id.:format' => 'posts#html_respond', :constraints => {:format => "html"}
match 'posts/:id.:format' => 'posts#json_respond', :constraints => {:format => "json"}

Upvotes: 1

Related Questions