【问题标题】:Ruby in Rails, destroy does not work in edit. routing to showRails 中的 Ruby,destroy 在编辑中不起作用。路由显示
【发布时间】:2014-02-23 16:16:29
【问题描述】:

我对销毁操作有疑问。 它在 index.html.erb 中工作得很好。 但我无法让它在edit.html.erb中工作 即使没有请求许可,它也会路由到节目。

这里的许多解决方案都说它与 jQuery 有关。正如你所看到的,我尝试了所有我能找到的。

<%= stylesheet_link_tag    "application" %>
    <!--Delete Problem in Edit-->
    <%#= javascript_include_tag :all %>
    <%#= javascript_include_tag :application %>
    <%#= javascript_include_tag :default %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>

有适合​​我情况的解决方案吗?

这是我在编辑中的删除按钮:

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", confirm: 'Are you sure?', method: :delete) do %>
<%= t "list.button_delete" %>
        <%#= link_to I18n.t(".list.delete"), contact, confirm: 'Are you sure?', method: :delete %>
        <%#= link_to 'delete', contact_path(@contact), :method => :delete %>
<% end %>

我也尝试了很多东西。

以下是动作:

def destroy
    #@contact = Contact.find(params[:id])
    @contact = current_user.contacts.find(params[:id])
    @contact.destroy
    redirect_to contacts_url,
                            alert: 'Successfully deleted the contact'
end

【问题讨论】:

  • 请看我更新的答案。

标签: ruby-on-rails ruby routing edit destroy


【解决方案1】:

替换

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", confirm: 'Are you sure?', method: :delete) do %>

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", data: {confirm: 'Are you sure?'}, data: {method: :delete}) do %>

应该是 data: {confirm: 'Are you sure?'} 而不是 confirm: 'Are you sure?'data: {method: :delete} 而不是 method: :delete

其中,link_to 方法将 confirm: 'Are you sure?' 内插为 data-confirm="Are you sure?"method: :delete 作为 data-method="delete"

content_tag 方法将confirm: 'Are you sure?' 插入为confirm="Are you sure?"method: :delete 作为method="delete",因此您的javascript 调用不会被调用。

【讨论】:

  • 我不理解 HTML 中的输出数据方法,但它可以工作。谢谢你。 :)
  • @Lintu 检查data-*link 的工作原理。尝试该页面上给出的示例。
【解决方案2】:

在您的destroy 操作中替换:

@contact = current_user.contacts.find(params[:id])

与:

@contact = @current_user.contacts.find(params[:id])

【讨论】:

  • 不幸的是它不起作用。它仍然路由显示,无需询问 并且从具有相同操作的索引中删除有错误消息:未定义的方法 `contacts' for nil:NilClass
  • 发布您的路线文件。显然current_user 变量是nil。你在哪里分配它?
  • root :to => 'contacts#index' devise_for :users 资源 :contacts
  • 我将它们分配给彼此:用户有很多,联系人有一个联系人模型:belongs_to :user 用户模型:has_many :contacts
  • @Lintu 这是你唯一的路线吗?如果是这样,那么您还需要为 destroy 操作添加路由。至于current_user 变量,必须在你使用它的控制器动作中赋值。
猜你喜欢
  • 1970-01-01
  • 2015-07-11
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2018-05-09
  • 2020-03-27
相关资源
最近更新 更多