Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - link_to with custom route

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?

like image 855
urSus Avatar asked Nov 14 '12 03:11

urSus


People also ask

What are nested routes in Rails?

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).

How do I link pages in Rails?

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.

What is the difference between resources and resource in Rails?

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.


1 Answers

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) %>
like image 84
Mischa Avatar answered Oct 19 '22 00:10

Mischa