良い一日、
編集および削除できる RoR 4 のリンクのリストを含む単純なフォームを作成しようとしています。
メインの投稿モデル ファイル controller->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)**
いつものように、あなたの助けに感謝します。