Say for instance I have a posts controller that currently has a method user_posts which shows all of the posts that are associated with the user with the associated id as so:
def user_posts
@user = User.find(params[:id])
@posts = @user.posts.all
end
I want the url to be: foo.com/my_posts when the posts have the same ID as my current_user; How would I do this? currently my routes are set up as so:
get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
I know that I could create an entirely new controller action for my_posts but I want to know if there is a way to do it in the config/routes.
If for example I am browsing throughout the site and tap on a link that says "user posts" I would expect to go the the users posts and if that user happens to be me I would like the url to show website.com/my_posts
If I understand well, you have a list of users (including the currently connected user) and each has a link 'user posts' to see the user's posts.
You can simply do:
views
In your views, change the user post link according to the user id. As you loop through your users, check if the
user's id is the same as the currently logged user. If yes, change the link to the/my_postsroute as follow:routes.rb
Add a
my_postsroute that points to the same controller method asuser/posts.controller
In your controller method, we need to instantiate the
@userto get its posts. If there is no:idin the params (like the/my_postsroute), then set the@userto the current_user. If an:idis passed, set the@userby fetching it from the db.No need to do checking in the routes.rb file. This is simple and more "Rails" like.
Is this what you are looking for?