【发布时间】:2016-12-01 14:41:58
【问题描述】:
我的 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 将关联复制到页面。您还可以看到我引用了 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
【问题讨论】:
-
@branch应该有一些错误,你能在branch.save行之后添加这个puts @branch.errors.full_mesasges看看它有什么错误。 -
好的,所以使用评估表达式。我收到错误“块无效”。所以我认为在复制它们时它没有通过验证。请参阅更新后的帖子,其中包含我在模型中进行的验证,但仍然意味着复制无法正常工作。