再会,
我正在尝试使用 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)**
一如既往,感谢您的帮助。