Search code examples
ruby-on-railshyperlinkroutesslim-lang

Rails -- How to write a link which will be called to call a action with a parameter in controller ?


Example, in my controller:

class GymController < ApplicatoinController
  def store(page)
     ...
  end
end

And now, I want call this action by a link in gym.html.slim:

- a ...

but how to call it by link format, and how to write route.rb file?


Solution

  • The answer depends on whether your store page belongs to a single Gym object OR to a collection of it:

    For a single object

    # app/controllers/gym_controller.rb
    class GymController < ApplicatoinController
      before_action :fetch_gym
    
      def store
        # ...
      end
    
      private
    
      def fetch_gym
        @gym = Gym.find(params.require(:id))
      end
    end
    
    # config/routes.rb
    resources :gyms, only: [] do
      get :store, on: :member
    end
    
    # gym.html.slim
    = link_to 'Store', store_gym_path(@gym)
    

    For a collection

    # app/controllers/gym_controller.rb
    class GymController < ApplicatoinController
      def store
        # ...
      end
    end
    
    # config/routes.rb
    resources :gyms, only: [] do
      get :store, on: :collection
    end
    
    # gym.html.slim
    = link_to 'Store', store_gym_path
    

    Read more on link_to and routing here.