Question

how do i make it work? This is an example url i need:

/name/posts/2

My routes.rb

  get "/:name", to: "categories#show" do
    resources :posts, only: [:show]
  end
Was it helpful?

Solution

app/config/routes.rb

scope path: '/:name' do
  resources :posts, only: [:show]
end

resources :posts, except: [:show]

This will pass the :name and :id params into your posts#show function.

app/controllers/posts_controller.rb

def show
  user = User.where(name: params[:name]).first
  @post = Post.where(['id = ? AND user_id = ?', params[:id], user.id])

  render @post
end

NOTE: This can be more Rails 4 friendly by using Strong Parameters.

OTHER TIPS

This will catch anything like /:name in the URLs and route it to the categories controller. Adding :path => "" means it will cut the resource identifier from the URL. So instead of having /categories/foobar you now get /foobar Then you just nest your post routes in the parent route.

resources :categories, :path => "" do
  resources :posts, :only => :show
end

Note that this kind of catch-all route is potentially very error prone as it catches everything, including crap you don't expect:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top