0

我的 Rails 应用程序中的 Pages 有以下模型:

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 将关联复制到页面。您还可以看到我引用了 PageTemplate 和 BlockTemplate。模板本身不应该重复,但通过外键的引用应该是重复的,因此我只为 include_association 指定块和内容。

但是,如果我在 上设置断点@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
4

1 回答 1

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
于 2016-12-05T14:20:38.357 回答