Reputation: 1173
I'm a new rails developer making an application where I have a user profile like: localhost:3000/posts
routing to localhost:3000/Charles
where Charles is the username.
So the code I'm using to do this looks like:
routes.rb
match "/:username" => "posts#index"
and then in my controller:
@user = User.find_by_username params[:username]
@search = Post.search do |query|
query.fulltext params[:search]
query.with(:user, @user.id)
end
this works great just for the post index, but I'd like to have posts/18 (for example) be routed to /username/posts/18.
So basically, I'm asking if there's a way to do something like this:
match "/:username" => "posts#index" do
resources :posts
end
Thanks for all help!
Upvotes: 2
Views: 284
Reputation: 17631
Try
scope ':username' do
resources :posts
end
bundle exec rake routes
posts GET /:username/posts(.:format) posts#index
POST /:username/posts(.:format) posts#create
new_post GET /:username/posts/new(.:format) posts#new
edit_post GET /:username/posts/:id/edit(.:format) posts#edit
post GET /:username/posts/:id(.:format) posts#show
PUT /:username/posts/:id(.:format) posts#update
DELETE /:username/posts/:id(.:format) posts#destroy
Upvotes: 1
Reputation: 1644
This
scope '/:username' do
resources :posts
end
produces what you want:
posts GET /:username/posts(.:format) posts#index
POST /:username/posts(.:format) posts#create
new_post GET /:username/posts/new(.:format) posts#new
edit_post GET /:username/posts/:id/edit(.:format) posts#edit
post GET /:username/posts/:id(.:format) posts#show
PATCH /:username/posts/:id(.:format) posts#update
PUT /:username/posts/:id(.:format) posts#update
DELETE /:username/posts/:id(.:format) posts#destroy
Upvotes: 2
Reputation: 2519
match "/:username/posts/:id" => "posts#show"
But that won't really help when you need to edits and such. So, try:
scope "/:username" do
resources :posts
end
That failing:
scope "/:username" do
get '' => "posts#index"
get 'posts/:id' => "posts#show"
end
Hopefully the first will work. Haven't tried it myself so forgive me, but I'm pretty sure that, in general, scope is what you want.
Upvotes: 1