代码之家  ›  专栏  ›  技术社区  ›  Rabbott

Rails确定来自的对象是否为更改的对象接受\u嵌套的\u属性\u?

  •  3
  • Rabbott  · 技术社区  · 15 年前

    我有一张收集文件的表格,我们称之为 文件夹 删除其中一个文件 添加新文件 二者都 (删除一个文件,然后添加另一个)

    1 回复  |  直到 15 年前
        1
  •  3
  •   Voldy    15 年前
    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? 它返回此记录是否已以任何方式更改(新的\u记录?,标记为要销毁?,更改了吗?),包括其嵌套的autosave关联是否也发生了类似的更改。

    您可以将特定于模型的逻辑从控制器移动到中的方法 folder 型号,e.q。 @folder.how_changed? ,它可以返回以下符号之一:add\u new\u file,:delete\u 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 方法 changed_for_autosave? 我只知道孩子们是怎么变的。这就是如何利用这些指标来实现你的目标。