首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从rails中的嵌套表单中删除元素

从rails中的嵌套表单中删除元素
EN

Stack Overflow用户
提问于 2021-02-19 13:43:45
回答 2查看 52关注 0票数 1

您好,我有我的路线在rails的方式:

代码语言:javascript
复制
  resources :users do
    resources :socials
  end

这是我的模型:

代码语言:javascript
复制
class User < ApplicationRecord
  has_many :socials, dependent: :destroy
  accepts_nested_attributes_for :socials
end

class Social < ApplicationRecord
  belongs_to :user
end

下面是我的socials控制器,用于销毁表socials中的一行,我不需要删除用户,只需要从嵌套的表单中删除带有id的socials中的一行:

代码语言:javascript
复制
<div class="container">
<%= form_with(model: @user, local: true) do |f| %>
 ...
  Social Media
    <div class="container m-3">
      <%= f.fields_for :socials, {class: 'inline-block m-3'} do | social |  %>

        <%= social.label :name, class: 'inline-block m-3'%>
        <%= social.text_field :name %>
        <%= social.label :link, class: 'inline-block m-3'%>
        <%= social.text_field :link %>
        *<%= link_to 'Delete', user_social_path(@user.social.id), method: :delete %> ->
        <hr>
      <% end %>
    </div>
  <p>
    <%= f.submit %>
  </p>
<% end %>

然后使用这个link_to,当我点击删除社会表时,我想删除行,我该怎么做呢?我使用的是ruby和rails的6.1.2.1版本

EN

回答 2

Stack Overflow用户

发布于 2021-02-20 16:55:58

我认为你不应该删除使用链接..

嵌套表单已经支持删除行的选项,您需要做的只是在社交中传递另一个键值对,即_destroy: true

在控制器端只允许强参数中的_destroy

在模型中将其定义为类似于accepts_nested_attributes_for :socials, allow_destroy: true

你还可以在UI上玩点花样,让它更吸引人。

  • _destroy定义了一个隐藏字段,默认选项为false。
  • 单击事件时使用Javascript添加用于删除的按钮。单击该按钮时,
  • 将隐藏该行并将_destroy字段的值更改为false

现在,当您要保存/更新它时,它将被删除。

参考资料:https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/NestedAttributes/ClassMethods.html

票数 1
EN

Stack Overflow用户

发布于 2021-02-19 15:15:58

代码语言:javascript
复制
<%= link_to "delete", [@user, @user.social], :method => :delete %>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66272329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档