Search code examples
ruby-on-railsurlroutescontroller-action

Change the url based on current_user - ROR


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


Solution

  • 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_posts route as follow:

    <% if user.id == current_user.id %>
      <%= link_to "My posts", my_posts_path %>
    <% else %>
      <%= link_to "User posts", user_posts_path(user) %>
    <% end %>
    

    routes.rb

    Add a my_posts route that points to the same controller method as user/posts.

    get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
    get 'my_posts', to: 'posts#user_posts', as: 'my_posts'
    

    controller

    In your controller method, we need to instantiate the @user to get its posts. If there is no :id in the params (like the /my_posts route), then set the @user to the current_user. If an :id is passed, set the @user by fetching it from the db.

    def user_posts
        @user = params[:id].present? ? User.find(params[:id]) : current_user
        @posts = @user.posts.all
    end
    

    No need to do checking in the routes.rb file. This is simple and more "Rails" like.

    Is this what you are looking for?