Search code examples
ruby-on-railsbutton-to

rails button_to current_user correct path


What path can I use to display a current_user's own listed products?

= button_to "View My Products", root_path, method: :get, class: "button"

Instead of root_path I tried to use @product.user.all which did not work.

Thanks!

edit:

            user GET    /users/:id(.:format)           users#show
     search_products GET    /products/search(.:format)     products#search
            products GET    /products(.:format)            products#index
                     POST   /products(.:format)            products#create
         new_product GET    /products/new(.:format)        products#new
        edit_product GET    /products/:id/edit(.:format)   products#edit
             product GET    /products/:id(.:format)        products#show
                     PATCH  /products/:id(.:format)        products#update
                     PUT    /products/:id(.:format)        products#update
                     DELETE /products/:id(.:format)        products#destroy
       welcome_index GET    /welcome/index(.:format)       welcome#index
                root GET    /                              welcome#index

and all of Devise's standard routes.


Solution

  • I think you want one product controller index action and association between user and products

    Then in products#index action

    def index
      @products = current_user.products
    end
    

    and your link will be

    = link_to 'View My Products', {controller: :products, action: :index}
    

    If your product#index action for non authenticated users then make that action conditional like @products = (current_user ? current_user.products : Product.all)