2

How can I create delete link_to in Rails app?

Votes controller

    class VotesController < ApplicationController

    def destroy
        @user = User.find(params[:id])
        @user.votes.pluck(:author_uid).delete(current_user.uid)
    end

end

Routes

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

What should I write in link_to in view?

I tried

= link_to 'Delete vote', {controller: "votes", action: "destroy"}, method: "delete"

and

= link_to 'Delete vote', vote_path(vote), method: :delete

users/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'

Of course it's not working. I'm sure I should fix it with routes, but I don't know how.

Please comment, if you need more information.

Thanks!

4

2 回答 2

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)
于 2013-11-11T10:05:19.337 回答
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'

正如我在对您的问题的评论中指出的那样,您还需要整理您的销毁操作;并且您的创建操作可能以类似方式受到怀疑;我没研究过。

于 2013-11-11T10:37:19.323 回答