使用Amoeba复制包含块和内容的页面

时间:2016-12-01 14:41:59

标签: ruby-on-rails amoeba-gem

我的rails应用程序中的页面有以下模型:

class Page < ActiveRecord::Base

  has_many :blocks
  has_many :contents, :through => :blocks

  validates :title, presence: true
  validates :content, presence: true
  validates :page_template_id, presence: true

  amoeba do
    enable
    include_association :blocks
    include_association :contents
  end

  def create_branch
    branch = self.amoeba_dup #should dup content and blocks too
    branch.branched_from = self.id #so we know what record it was copied from
    branch.status = 0 #set this new copy to draft
    branch.save #save the branch
    branch #return the branch
  end

end

所以页面有块,块有内容。

它们的模型如下:

class Block < ActiveRecord::Base
  belongs_to :page
  belongs_to :block_template
  has_many :contents
  validates :title, presence: true
  validates :block_template_id, presence: true
  validates :page_id, presence: true
end

class Content < ActiveRecord::Base
  belongs_to :block
  validates :name, presence: true
  validates :content, presence: true
  validates :block_id, presence: true
end

我想做的是当我在控制器中调用它时:

  def branch
    @page = Page.find(params[:id])
    @branch = @page.create_branch
    redirect_to edit_page_path(@branch), :notice => 'Draft created!'
  end

它应该复制页面及其块和内容。就像在数据库中实际创建这些记录的新版本一样,但所有关联都是机智的!我正在使用Amoeba gem来复制与Page的关联。您还可以看到我引用PageTemplate和BlockTemplate。模板本身不应该重复,但应该通过外键引用,因此我只是为include_association指定Block和Content。

但是,如果我在@branch上设置了一个断点,它看起来拥有所有数据但没有ID,因此重定向失败。它没有ID,因为它没有被正确复制......任何想法为什么?

应该创建页面,块和内容的副本。

我尝试了像clone这样的clone: [:blocks, :contents]方法,但这给了我一个clone取0参数的错误......

我可以使用手动实现我想要的东西:

def create_branch
  new_page = self.dup
  new_page.branched_from = self.id
  new_page.status = 0
  new_page.save
  # duplicate the blocks and contents
  self.blocks.each do |block|
    new_block = block.dup
    new_block.page_id = new_page.id
    new_block.save
    block.contents.each do |content|
      new_content = content.dup
      new_content.block_id = new_block.id
      new_content.save
    end
  end
  # finally return the new page
  new_page
end

1 个答案:

答案 0 :(得分:0)

您可以在块中包含所需的所有选项,对于Contents关系,您可以从Block类创建它,如下所示:

class Page < ActiveRecord::Base
  ...
  amoeba do
    include_association :blocks
    set :status => 0
    customize(lambda { |original_page, new_page|
      new_page.branched_from = original_page.id
    })
  end
  .....
  def create_branch 
    branch = self.amoeba_dup
    branch.save
    branch
  end
end

当克隆Block时,我们将获得克隆内容的代码:

class Block < ActiveRecord::Base
  .......
  amoeba do
    include_association :contents
    set :status => 0
    customize(lambda { |original_block, new_block|
      new_block.page_id = original_page.id
    })
  end
  ....... 
end

 class Content < ActiveRecord::Base
  ....... 
  amoeba do
    enable
  end
  ....... 
 end