Search code examples
ruby-on-railsactiverecordlink-toscaffold

Rails link_to Last Scaffold Item


I'm working on a learning platform that at this stage has users, an admin, and 'feeds' (pages with learning content). I would like to create a link that would take users to the newest feed created by the admin. In the console, I could locate this record with 'feed.last'.

Here are the routes in my application:

                   feeds GET    /feeds(.:format)               feeds#index
                         POST   /feeds(.:format)               feeds#create
                new_feed GET    /feeds/new(.:format)           feeds#new
               edit_feed GET    /feeds/:id/edit(.:format)      feeds#edit
                    feed GET    /feeds/:id(.:format)           feeds#show
                         PATCH  /feeds/:id(.:format)           feeds#update
                         PUT    /feeds/:id(.:format)           feeds#update
                         DELETE /feeds/:id(.:format)           feeds#destroy
        new_user_session GET    /users/sign_in(.:format)       devise/sessions#new
            user_session POST   /users/sign_in(.:format)       devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy
           user_password POST   /users/password(.:format)      devise/passwords#create
       new_user_password GET    /users/password/new(.:format)  devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                         PATCH  /users/password(.:format)      devise/passwords#update
                         PUT    /users/password(.:format)      devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel
       user_registration POST   /users(.:format)               devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit
                         PATCH  /users(.:format)               devise/registrations#update
                         PUT    /users(.:format)               devise/registrations#update
                         DELETE /users(.:format)               devise/registrations#destroy
                    root GET    /                              pages#home

Is there a way I could write a 'link_to' action to handle this (ex: <%= link_to "Latest Feed", ___________ %>)?


Solution

  • There are 2 ways to do this. You could either add a member action to your feeds resource in routes.rb named latest (or whatever you like). Then you would create a corresponding controller action and view. In the controller action you would set @feed = Feed.last. The second option would be to link to the index or show action, add a GET parameter to the URL and then put logic in the controller action that returns Feed.last if the parameter is set.