I am implementing a like system in my rails app using David Celis gem called Recommendable. I've gotten everything to work in the console but I can't get the right routes and I'm getting the "No route matches [GET] "/categories/1/posts/1/like" error.
I have the following in my models:
class Category < ActiveRecord::Base
has_many :posts, :dependent => :destroy
extend FriendlyId
friendly_id :name, use: :slugged
end
class Post < ActiveRecord::Base
belongs_to :category
end
In my Post Controller I have:
class PostsController < ApplicationController
before_filter :authenticate_user!
before_filter :get_category
def like
@post = Post.find(params[:id])
respond_to do |format|
if current_user.like @post
else
flash[:error] = "Something went wrong! Please try again."
redirect_to show_post_path(@category, @post)
end
end
end
end
In my routes I have:
resources :categories do
resources :posts do
put :like, :on => :member
end
end
match 'categories/:category_id/posts/:id', :to => 'posts#show', :as => 'show_post'
Can someone please point at my errors? I can get the PUT to work but I dont know where the GET error is coming from as I am trying to redirect back to the post if an error occurs when the user like's a certain post. Thank you in advance.
EDIT:
In my view I have:
- title "#{@post.class}"
%p#notice= notice
%p
%b Title:
= @post.title
%p
%b Description:
= @post.description
%p
%b Likes:
= @post.liked_by.count
= link_to 'Edit', edit_category_post_path(@post)
\|
= link_to 'Back', category_posts_path
\|
= link_to 'Like', like_category_post_path(@post)
Replace:
= link_to 'Like', like_category_post_path(@post)
with:
= link_to 'Like', like_category_post_path(@category, @post), method: :put
Or, as I like it:
= link_to 'Like', [@category, @post], method: :put
I think your like
has to be:
def like
@post = Post.find(params[:id])
respond_to do |format|
format.html do
if current_user.like @post
flash[:notice] = "It's ok, you liked it!"
redirect_to :back
else
flash[:error] = "Something went wrong! Please try again."
redirect_to show_post_path(@category, @post)
end
end
end
end