如何创建删除链接

时间:2013-11-11 10:00:21

标签: ruby-on-rails routes ruby-on-rails-4

如何在Rails应用程序中创建删除link_to?

投票控制器

    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

我应该在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'

当然它不起作用。我确定我应该用路线解决它,但我不知道如何。

如果您需要更多信息,请发表评论。

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个

= link_to('Delete', vote_path(vote.id),:method => :delete, :confirm => "Are you sure you want to delete?")  
OR       
= link_to('Delete',{controller: :votes, id: vote.id, action: :destroy}, confirm: "Are you sure you want to delete ?", method:  :delete)

答案 1 :(得分:2)

你的第二个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'

正如我在你的问题评论中所指出的那样,你还需要理清你的摧毁行动;并且您的创建行为可能以类似的方式受到怀疑;我没有研究过它。