0

I got an error

No route matches [POST] "/article/1/like"

My articles_controller.rb is.

 def like
    @article = article.all.find(params[:id])
    Like.create(user_id: current_user.id, article_id: @article.id)
    redirect_to articles_path(@article)
  end

This is my index page.

 <% if article.liked?(current_user) %>
                    <%= button_to "like", like_path(article), methode:"put", desabled: true %>
                  <% else %>
                    <%= button_to "like", like_path(article), methode:"put" %>
                  <% end %> 

and routes.rb is

    Rails.application.routes.draw do
  get 'static_pages/landing_page'
  get 'static_pages/dashboard'
  

  devise_for :users
  resources :users


  resources :articles do
    resources :comments
  end


  put '/article/:id/like', to: 'article#like', as: 'like'

  root "articles#index"
end

I am writing this code from a website given below. enter link description here

1
  • 1
    methode:"put" is not a valid attribute, try method: :put Also your link doesnt work for me. EDIT: I dont think desabled: true will work either, try disabled
    – Haumer
    Commented Oct 1, 2022 at 14:38

2 Answers 2

0

The idomatically correct way to add additional actions to a resource is:


resources :articles do
  put :like
  resources :comments
end

This creates the route /articles/:article_id/like(.:format) - not that articles is plural.

<%= button_to "like", article_like_path(article), method: :put, disabled: article.liked?(current_user) %>
2
  • It can be debated if this is actually a the most RESTful design. I would use POST /articles/:id/likes instead as you're actually creating a resource and not updating.
    – max
    Commented Oct 1, 2022 at 15:44
  • shouldn't the correct syntax be put :like, on: :member ? (according to the Rails doc cited) Commented Oct 1, 2022 at 17:32
0
    def like
    @article = article.all.find(params[:id])
    Like.create(user_id: current_user.id, article_id: @article.id)
    redirect_to articles_path(@article)
  end

in like method use params[:article_id] instead of params[:id]

Not the answer you're looking for? Browse other questions tagged or ask your own question.