您需要的是奇异资源。
路线.rb
resources :items do
resource :like, only: [:create, :destroy]
end
likes_controller.rb
class LikesController < ApplicationController
before_action :load_likeable
def create
@like = Like.where(likeable: @likeable, user: current_user).first_or_create
redirect_back(fallback_location: @likeable)
end
def destroy
@like = Like.find_by(likeable: @likeable, user: current_user).destroy
redirect_back(fallback_location: @likeable)
end
private
def load_likeable
klass = [Recording].detect { |c| params["#{c.name.underscore}_id"] }
@likeable = klass.find(params["#{klass.name.underscore}_id"])
end
end
likes_helper.rb
module LikesHelper
def like_button_for(item)
if item.liked
form_tag recording_like_path(item), method: :delete do
button_tag "UnLike"
end
else
form_tag recording_like_path(item), method: :post do
button_tag "Like"
end
end
end
end
item.liked 是来自 Item 模型的方法