Does Rails determine if objects from accepts_nested_attributes_ have changed for objects?

I am aware of the main dirty methods of indicators for rails that work if the direct attributes of an object change, I wonder how to determine if my children are updated.

I have a form for a collection of files, we will call it a folder . The accepts_nested_attributes_for folder: files. I need to determine (as part of the controller action) whether the files that are inside the params hash are different from those that are in db. So, the user deleted one of the files , whether they added a new file or and (delete one file and add another)

I need to determine this because I need to redirect the user to another action if they deleted the file, instead of adding a new file, not just the updated attributes of the folder.

+3
source share
1 answer
def update
  @folder = Folder.find(params[:id])
  @folder.attributes = params[:folder]

  add_new_file = false
  delete_file = false
  @folder.files.each do |file|
    add_new_file = true if file.new_record? 
    delete_file = true if file.marked_for_destruction?
  end  

  both = add_new_file && delete_file

  if both
    redirect_to "both_action"
  elsif add_new_file
    redirect_to "add_new_file_action"
  elsif delete_file
    redirect_to "delete_file_action"
  else
    redirect_to "folder_not_changed_action"
  end 
end

Sometimes you want to know that a folder has been changed without determining how. In this case, you can use the mode autosavein your association:

class Folder < ActiveRecord::Base 
  has_many :files, :autosave => true
  accepts_nested_attributes_for :files
  attr_accessible :files_attributes
end

Then in the controller you can use @folder.changed_for_autosave?that returns regardless of whether this record was changed in any way (new_record ?, marked_for_destruction ?, changed?), Including whether any of its nested autosave associations also changed.

Updated.

folder, e.q. @folder.how_changed?, : add_new_file,: delete_file .. ( , , ). .

case @folder.how_changed?
  when :both
    redirect_to "both_action"
  when :add_new_file
    redirect_to "add_new_file_action"
  when :delete_file
    redirect_to "delete_file_action"
  else
    redirect_to "folder_not_changed_action"
end

2 : new_record? marked_for_destruction? , Rails in-box changed_for_autosave? , - . .

+3

Source: https://habr.com/ru/post/1765216/


All Articles