Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.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 从mixin添加关联,而不覆盖现有关联_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 从mixin添加关联,而不覆盖现有关联

Ruby on rails 从mixin添加关联,而不覆盖现有关联,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有许多课程,如下所示: class Event < ActiveRecord::Base include PreventUpdate has_many :participants, conditions: ... has_many :venues, conditions: ... has_many :companies, conditions: ... end 唯一的问题是,动态添加的语句和原始语句有许多语句相互覆盖。它会覆盖,这取决于模块在Include类中的位置

我有许多课程,如下所示:

class Event < ActiveRecord::Base
  include PreventUpdate

  has_many :participants, conditions: ...
  has_many :venues, conditions: ...
  has_many :companies, conditions: ...
end
唯一的问题是,动态添加的语句和原始语句有许多语句相互覆盖。它会覆盖,这取决于模块在Include类中的位置


是否有任何方式可以使动态添加的声明和原始声明“累积”,即模块的声明可以简单地添加到原始声明上而不被覆盖?

这是未经测试的,但您应该能够做到:

included do 
  self.reflect_on_all_associations(:has_many).each do |assoc|
    assoc.options.merge!(:before_add => :prevent_update)
  end
end
这将要求关注点
包含
有许多
声明之后。如果要在它们之前执行
包含
,可以添加:

module ClassMethods
  def modify_associations
    self.reflect_on_all_associations(:has_many).each do |assoc|
      assoc.options.merge!(:before_add => :prevent_update)
    end
  end
end
然后:

# ...    
has_many :companies, conditions: ...
modify_associations
编辑

这应该起作用:

included do 
  self.reflect_on_all_associations(:has_many).each do |assoc|
    has_many assoc.name, assoc.options.merge(:before_add => :prevent_update)
  end
end

我看到这确实正确地更新了assoc.options,重新加载了页面,但是当添加实际发生时,它仍然没有收到before_add回调(我将模块包括在原始关联行下面)。什么可以工作,但对于生产来说太难看了。。。我可以添加你的assoc.options.merge!方法(很抱歉,我不知道如何格式化)assoc_string=“has_many:#{assoc.name}”;每一个选项都是k,v;值=v.是否为a?(符号)?“:#{v}”:“#{v}”;我刚刚用一个解决方案(你的原始想法和我的原始答案的组合)更新了我的答案,这个解决方案似乎有效。。。
included do 
  self.reflect_on_all_associations(:has_many).each do |assoc|
    has_many assoc.name, assoc.options.merge(:before_add => :prevent_update)
  end
end