ruby-on-rails - 如何创建删除链接

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

如何在 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/

相关文章:

ruby-on-rails - 将两个数据库列合并为一个数组列

ruby-on-rails - 是否可以在 Rails 中缓存自定义 sql 查询?

ruby-on-rails - heroku toolbelt 打破 rails

c# - ASP.NET MVC中如何获取所有事件参数(二)

mysql - 充当 Taggable On taggable_id 增量如此之快

ruby - 如何最好地防范未定义的属性?

ruby-on-rails - 提交表单后我想留在同一页面并显示 :notice messages

node.js - NodeJS - 触发错误的 Express 路线

symfony - Symfony 2 URL 结构中的可选区域性参数?

javascript - 在启用 turbolinks 的情况下重新渲染特定的 js 文件