I am new to Rails so please have patience.
I wanted to implement "like" on my canteen model, so I created a custom route inside my canteen resource
resources :canteens do
resources :meals
resources :comments
match "/like", :to => "canteens#like", :as => "like"
end
and therefore created this action inside canteens controller, where I just increment a counter
def like
canteen = Canteen.find(params[:canteen_id])
Canteen.increment_counter("likes_count", canteen.id)
redirect_to canteen
end
So, manually entering the URL localhost:3000/canteens/1/like works just fine, however obviously I want to create a button so I did a
<h2>Likes count</h2>
<p><%= @canteen.likes_count %> likes</p>
<p><%= link_to "Like this canteen", canteen_like_path %></p>
And it doesn't work. I checked rake routes and it's there (canteen_like). What am I doing wrong?
In a nested route, the belongs_to (child) association is always nested under the has_many (parent) association. The first step is to add the nested routes like so: In the above Rails router example, the 'index' and 'show' routes are the only nested routes listed (additional or other resources can be added).
Instead of using the anchor ( <a> ) HTML tags for links, Rails provides the link_to helper to add links. Remember, Ruby code in the views must be enclosed in a <% %> or a <%= %> tag.
Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.
You have to pass a Canteen
object to the path. If you don't do that Rails doesn't know which canteen you meant:
<%= link_to "Like this canteen", canteen_like_path(@canteen) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With