3

再会,

我正在尝试使用 RoR 4 中可以编辑和删除的链接列表创建简单的表单。

我已经允许在主后模型文件控制器“销毁”->posts.rb

class Post < ActiveRecord::Base
has_many(:links, :dependent => :destroy)

accepts_nested_attributes_for :links,    :reject_if => lambda { |a| a[:link].blank? },   :allow_destroy => true

我在创建和更新控制器上接受销毁参数

    def create
    @new_post = Post.new(params[:post].permit(:title, :body, :tag_list,     links_attributes:[:link, :_destroy]))

    if @new_post.save
        redirect_to posts_path, :notice =>"Saved!"
    else
        render new
    end
end

def update
    @post_to_update = Post.find(params[:id])

    if @post_to_update.update(params[:post].permit(:title, :body, :tag_list,    links_attributes:[:link, :_destroy]))
        redirect_to posts_path, :notice =>"Updated!"
    else
        render edit
    end
end

我正在使用 jQuery 删除链接字段并将其销毁值设置为“true”

<h1> Edit post </h1>
<%= form_for @post_to_edit do |f|%>
    Title <%= f.text_field :title %> </br>
    Body <%= f.text_area :body %> </br>
    <%= f.fields_for :links do |b| %>
    <li class = "enter_link">
        <%= b.text_field :link %>
        <%= b.hidden_field :_destroy %>
        <%= link_to_function "Remove", "remove_fields(this)" %></br>
    </li>
    <% end %>
    Tags <%= f.text_field :tag_list %>
    <%= f.submit "Update that bitch!" %>
<% end %>

Javascript

function remove_fields(link) {
    $(link).prev("input[type=hidden]").val("true");
    $(link).closest(".enter_link").hide();

}

这就是问题所在:假设我有一个包含 3 个链接的列表

"link 1"
"link 2"
"link 3"

我希望通过删除链接号 2 和 3 来编辑该列表。一旦我按下更新,销毁参数就会传递给控制器​​,但它不会删除原始行。

现在我会得到以下列表

"link 1"
"link 2"
"link 3"
**"link 1" (again, after removing link number 2 and 3)**

一如既往,感谢您的帮助。

4

2 回答 2

2

改变这个:

def update
    @post_to_update = Post.find(params[:id])

    if @post_to_update.update(params[:post].permit(:title, :body, :tag_list,    links_attributes:[:link, :_destroy]))
        redirect_to posts_path, :notice =>"Updated!"
    else
        render edit
    end
end

对此:

def update
    @post_to_update = Post.find(params[:id])

    if @post_to_update.update(
                         params[:post].permit(:title, :body, :tag_list, 
                         ## add `:id` to this one   
                         links_attributes:[:id, :link, :_destroy])
                         ##
                         )
        redirect_to posts_path, :notice =>"Updated!"
    else
        render edit
    end
end

id你必须在你的参数中允许links_attributes,这样记录就不会被重复并且_destroy可以工作

于 2014-09-27T20:56:18.597 回答
2

让我让你的生活更轻松,并推荐这个名为 Cocoon 的宝石(https://github.com/nathanvda/cocoon

它创建简单的嵌套表单。

只需将此代码粘贴到您的发布表单视图中。

  f.fields_for :links do |link|
  render 'link_fields', :f => link
  link_to_add_association 'add link', f, :tasks

使用 cocoon,嵌套表单需要一个部分,因此创建一个名为 _link_fields.html.erb 的文件

并在里面确保将所有内容都放在一个 div 中。他们的文档对此并不清楚,但根据经验,我确实知道这是必需的。

<div class="nested-fields">
f.label :link
f.text_field :link
link_to_remove_association "remove link", f
</div>

就是这样!

于 2013-09-06T21:46:20.407 回答