Rails 确定来自 accepts_nested_attributes_for 对象的对象是否已更改?

Rab*_*ott 5 ruby-on-rails

我知道 rails 的基本脏指示符方法,如果对象的直接属性发生更改,这些方法会起作用,我想知道如何确定我的孩子是否已更新..

我有一个文件集合的表格,我们称之为文件夹。一个文件夹 accepts_nested_attributes_for :files。我需要确定(在控制器操作中)是 params 哈希中的文件是否与 db中的文件不同。那么,用户是否删除了其中一个文件,他们是否添加了new file,或两者(删除一个文件,然后添加另一个)

我需要确定这一点,因为如果用户删除了一个文件,而不是添加一个新文件,或者只是更新了文件夹的属性,我需要将用户重定向到不同的操作。

Vol*_*ldy 3

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
Run Code Online (Sandbox Code Playgroud)

有时您想知道文件夹已更改,但不确定如何更改。autosave在这种情况下,您可以在关联中使用模式:

class Folder < ActiveRecord::Base 
  has_many :files, :autosave => true
  accepts_nested_attributes_for :files
  attr_accessible :files_attributes
end
Run Code Online (Sandbox Code Playgroud)

然后在控制器中,您可以使用@folder.changed_for_autosave?它返回该记录是否已以任何方式更改(new_record?,marked_for_destruction?,更改?),包括其任何嵌套自动保存关联是否同样更改。

更新。

folder您可以将模型特定逻辑从控制器移动到模型 eq中的方法@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
Run Code Online (Sandbox Code Playgroud)

该解决方案使用 2 种方法:new_record?marked_for_destruction?在每个子模型上,因为 Rails内置方法changed_for_autosave?只能告诉子项被更改,而无法知道如何更改。这就是如何使用这些指标来实现您的目标的方法。

  • 我不喜欢在控制器中做很多逻辑,这似乎是一种非常迂回的做事方式,我认为会有办法使用 Rails 提供的脏指示器。 (2认同)