Tôi đã đọc và nghiên cứu trong khoảng 3 ngày nay. Đây là phương sách cuối cùng của tôi.accept_nested_attributes_for rails 4 không xóa
land.rb:
has_many :uploads , :dependent => :destroy
accepts_nested_attributes_for :uploads, :allow_destroy => true,:reject_if => :all_blank
upload.rb
belongs_to :land
_land_form_partial.html.erb
<%= form_for land , :html => {:multipart => true} do |f| %>
<%= f.fields_for :uploads do |builder| %>
<div class="land_fields">
<%= builder.label :filename, "Image" %>
<%= builder.text_field :filename %> <br/>
Delete: <%= builder.check_box :_destroy %>
</div>
<% end %>
#... buttons and other fields
<% end %>
lands_controller.rb
def update
if @land.update_attributes(land_params)
flash[:success] = "Land updated"
redirect_to lands_path
else
flash[:alert] = @land.errors.full_messages.first
redirect_to edit_land_path
end
end
def land_params
params.require(:land).permit(uploads_attributes: [ :id, :filename ] )
end
Khi tôi thêm nội dung nào đó vào trường văn bản và cập nhật nó, tất cả các cập nhật đều đúng. Nếu tôi nhấp vào hộp kiểm, nó sẽ không xóa trường.
Ai đó có thể làm sáng tỏ điều này không?
Ngoài ra tôi đã thử awesome_nested_fields vẫn mọi thứ hoạt động ngoại trừ việc xóa bản ghi thực.
cảm ơn bạn trước.
EDIT: Giải pháp: (Tôi muốn đưa giải pháp trong câu hỏi trong trường hợp ai đó muốn xem nó trên điện thoại di động như tôi ghét khi tôi không thể nhìn thấy các giải pháp ngay lập tức)
Nhờ @nTraum
def land_params
params.require(:land).permit(uploads_attributes: [ :id, :filename, :_destroy ] )
end
Và tất cả sẽ dandy :)
Tôi đã gặp vấn đề tương tự nhưng trong trường hợp của tôi, tôi đã bỏ qua trường id: id. Sau đó, nếu bạn muốn xóa một mô hình lồng nhau, bạn cần phải cho phép: id và: _detroy các thuộc tính của mô hình lồng nhau. –