Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord中的延迟保存_Ruby On Rails_Activerecord_Delayed Execution - Fatal编程技术网

Ruby on rails ActiveRecord中的延迟保存

Ruby on rails ActiveRecord中的延迟保存,ruby-on-rails,activerecord,delayed-execution,Ruby On Rails,Activerecord,Delayed Execution,Shortly:是否有标准的Rails功能来标记模型实例进行延迟保存(例如m.delay\u save!),然后通过单个调用保存所有标记的模型(例如DelaysManager.commit!) 详细地: 考虑用例: 我需要用两种不同的方法更新模型X的实例: def f1 x = get_instance_of_x x.a = 'A' x.save! end def f2 x = get_instance_of_x x.b = 'B' x.save! end ... de

Shortly:是否有标准的Rails功能来标记模型实例进行延迟保存(例如
m.delay\u save!
),然后通过单个调用保存所有标记的模型(例如
DelaysManager.commit!

详细地

考虑用例: 我需要用两种不同的方法更新模型X的实例:

def f1
  x = get_instance_of_x
  x.a = 'A'
  x.save!
end

def f2
  x = get_instance_of_x
  x.b = 'B'
  x.save!
end
...
def g
  f1
  f2
end
这里的问题是g保存X的实例两次。我想做一次。我可以移动
save的调用到方法g,但在更复杂的情况下,g可能不知道需要保存哪些对象。所以我想让它看起来像这样:

def f1
  x = get_instance_of_x
  x.a = 'A'
  x.delay :save!
end

def f2
  x = get_instance_of_x
  x.b = 'B'
  x.delay :save!
end
...
def g
  f1
  f2
  DelaysManager.commit
end

class ActiveRecord::Base
  def delay(*args)
    DelaysManager.delay(self, *args)
  end
end

class DelaysManager
  @@delays = []
  def self.delay(*args)
    @@delays << args
  end

  def self.commit
    @@delays.each { |object, *args| object.public_send(*args) }
    @@delays.clear
  end
end 
def f1
x=获取\u x的\u实例\u
x、 a='a'
x、 延迟:救命!
终止
def f2
x=获取\u x的\u实例\u
x、 b='b'
x、 延迟:救命!
终止
...
def g
f1
f2
DelaysManager.commit
终止
类ActiveRecord::Base
def延迟(*args)
DelaysManager.delay(self,*args)
终止
终止
类延迟管理器
@@延迟=[]
def自延迟(*args)

@@延迟您可以通过将修改的对象收集到数组中来解决此问题。然后,您只需在它们上使用saveall。当然,当您获得一个已经修改过的对象的实例时,您必须检查它是否存在于数组中

def f1
  x = get_instance_of_x(params)
  x.a = 'A'
end

def f2
  x = get_instance_of_x(params)
  x.b = 'B'
end
...
def g
  @array_of_x = []
  f1
  f2
  commit
end

def get_instance_of_x(params)
  x = @array_of_x.select{|a| a.id == params[:id]} || X.find(params)
  @array_of_x << x unless @array_of_x.include(x)
  x
end

def commit
  @array_of_x.each(&:save)
end
def f1
x=获取x的实例(参数)
x、 a='a'
终止
def f2
x=获取x的实例(参数)
x、 b='b'
终止
...
def g
@数组_of_x=[]
f1
f2
犯罪
终止
def get_实例_of_x(参数)
x=@array_of_x.选择{| a | a.id==params[:id]}| | x.find(params)

@array\u of_x示例实现的思想正是自动维护数组。您的示例将对象保存在数组中的次数与包含在数组中的次数相同。由于使用了ActiveRecord,所以只保存更改,但如果在保存之前在某个地方覆盖并检查了相同的属性,则可能会导致问题。当然,这意味着大量的数据库使用。我的将其压缩一点,并且在保存之前可以使用更改的值。如果您对您的实现感到满意,那么我不太理解您的问题。