Rails - link_to with custom route

I am new to Rails, so please be patient.

I wanted to implement an “how” on my dining room model, so I created my own route inside my dining room resource.

resources :canteens do resources :meals resources :comments match "/like", :to => "canteens#like", :as => "like" end 

and therefore created this action inside the messes controller, where I just increment the counter

 def like canteen = Canteen.find(params[:canteen_id]) Canteen.increment_counter("likes_count", canteen.id) redirect_to canteen end 

So manually entering the localhost url: 3000 / canteens / 1 / like works very well, however obviously I want to create a button for me to do

 <h2>Likes count</h2> <p><%= @canteen.likes_count %> likes</p> <p><%= link_to "Like this canteen", canteen_like_path %></p> 

And it does not work. I checked the rake routes, and there (the dining room). What am I doing wrong?

+4
source share
1 answer

You need to pass the Canteen object to the path. If you do not, Rails does not know which of the canteens you had in mind:

 <%= link_to "Like this canteen", canteen_like_path(@canteen) %> 
+10
source

Source: https://habr.com/ru/post/1445917/


All Articles