Rails确定来自accepts_nested_attributes_for对象的对象是否发生了变化?

时间:2010-09-17 02:07:14

标签: ruby-on-rails

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

我有一个文件集合表单,我们称之为文件夹。一个文件夹accepted_nested_attributes_for:files。我需要确定的(在控制器操作中)是params散列内的文件是否与db中的文件不同。所以,用户是否删除了其中一个文件,他们添加新文件,还是两者(删除一个文件,然后添加另一个文件)

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

1 个答案:

答案 0 :(得分: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

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

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

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

<强>更新

您可以将模型特定逻辑从控制器移动到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

此解决方案在每个子模型上使用两种方法:new_record?marked_for_destruction?,因为Rails in-box 方法changed_for_autosave?只能告诉孩子们已更改没有怎么样。这就是如何使用这些指标来实现目标的方式。