I am unable to get the "like" action to work.
I am basing my action on the Raiscast no 364:
I believe my problem lies with the route:
resources :polls do
resources :likes, only: [], defaults => { :likeable => 'poll' } do
member { post :like }
end
end
Has defined the following route:
like_poll_like POST /polls/:poll_id/likes/:id/like(.:format) likes#like {:likeable=>"poll"}
I see here that the route is looking for an id for both the poll and the like however the controller action is to create a new row for in the likes table for the poll so there is no id for the like.
My like controller is:
class LikesController < ApplicationController
before_filter :load_likeable
def like
like = @likeable.likes.new(value: params[:value], user_id: current_user)
if like.save
redirect_to :back, notice: "Thank you for voting."
else
redirect_to :back, alert: "Unable to vote, perhaps you already did."
end
end
private
def like_params
params.require(:like).permit(:value)
end
def load_likeable
resource, id = request.path.split('/')[3,4]
@likeable = resource.singularize.classify.constantize.find(id)
end
def likeable_id
params[(params[:likeable].singularize + "_id").to_sym]
end
end
Here is the helper I am unable to get to work:
<%= link_to "Click here", polymorphic_url(poll, action: :like, value: 1), method: "post" %> to vote for <%= poll.option %>
This returns the following error:
undefined method `like_poll_url' for #<#<Class:0x007f4dbf3d4668>:0x007f4dbf308ba8>
I do not want to move the like action into the polls controller as likes is polymorphic and the same functionality will be reused.
Aucun commentaire:
Enregistrer un commentaire