如何在 Rails 应用中创建删除 link_to?
投票 Controller
class VotesController < ApplicationController
def destroy
@user = User.find(params[:id])
@user.votes.pluck(:author_uid).delete(current_user.uid)
end
end
路线
votes_path GET /votes(.:format) votes#index
POST /votes(.:format) votes#create
new_vote_path GET /votes/new(.:format) votes#new
edit_vote_path GET /votes/:id/edit(.:format) votes#edit
vote_path GET /votes/:id(.:format) votes#show
PATCH /votes/:id(.:format) votes#update
PUT /votes/:id(.:format) votes#update
DELETE /votes/:id(.:format) votes#destroy
View 中的link_to应该写什么?
我试过了
= link_to 'Delete vote', {controller: "votes", action: "destroy"}, method: "delete"
和
= link_to 'Delete vote', vote_path(vote), method: :delete
用户/index.html.haml
- @vk.friends.get(uid: current_user.uid, fields: fields) do |friend|
%td.span
.centred
.image
.circled
= image_tag friend.photo_medium
%span= friend.uid
%span= link_to "#{friend.first_name} #{friend.last_name}", "http://vk.com/id#{friend.uid}", target: "_blank"
%span= define_age(friend) == '' ? define_sex(friend) : define_sex(friend) + ', ' + define_age(friend)
- if current_user.user_votes.pluck(:recipient_uid).include?(friend.uid)
= link_to('Delete',{controller: :votes, id: vote.id, action: :destroy}, confirm: "Are you sure you want to delete ?", method: :delete)
- else
= link_to 'Vote', {controller: "votes", action: "create", uid: friend.uid}, method: "post", confirm: "You sure", class: 'button medium pink'
当然是不行的。我确信我应该用路线来修复它,但我不知道如何。
如果您需要更多信息,请发表评论。
谢谢!
最佳答案
从语法上来说,你的第二个link_to
没问题。问题是 vote
未定义。在您看来,请尝试以下操作:
%span= define_age(friend) == '' ? define_sex(friend) : define_sex(friend) + ', ' + define_age(friend)
- vote = current_user.user_votes.find_by_recipient_uid(friend.uid).first
- if vote
= link_to('Delete', vote, confirm: "Are you sure you want to delete ?", method: :delete)
- else
= link_to 'Vote', {controller: "votes", action: "create", uid: friend.uid}, method: "post", confirm: "You sure", class: 'button medium pink'
您还需要整理您的销毁操作,正如我在您的问题的评论中指出的那样;并且您的创建操作可能会以类似的方式受到怀疑;我没研究过。
关于ruby-on-rails - 如何创建删除链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19903495/