Rails如何手动创建没有表单的子对象

时间:2012-07-05 23:04:08

标签: ruby-on-rails-3 polymorphic-associations

我想知道在不使用表单的情况下以编程方式为父级生成单个子对象的最佳实现是什么。

在我的情况下,我有一个现有的论坛系统,我想通过评论绑定到我的上传系统。我想手动创建一个子论坛对象,以便在创建上传的同一个创建操作中讨论所述上传。这两个模型的关系如下:

儿童论坛:

class Forum < ActiveRecord::Base
   ...
   belongs_to :upload
end

父上传:

class Upload < ActiveRecord::Base
   ...
   has_one :forum
end

我在考虑以下几点:

class UploadsController < ApplicationController
  ...
  def create
    #Create the upload and a new forum + initial post to discuss the upload
    @upload = Upload.new(params[:upload])
    @forum = Forum.new(:upload_id => @upload.id, :title => @upload.name...)
    @first_post = Post.new(:forum_id => @forum.id....)    
    if @upload.save && @topic.save && @first_post.save
      redirect_to :action => "show", :id => @upload.id
    else
      redirect_to :action => "new"
    end 
  end

end

这与我想要做的非常接近,但在保存父对象之前不会生成父ID。我可以做类似的事情:

@upload.save 
@forum = Forum.new(:upload_id => @upload.id...
@forum.save....

但是我认为只有在所有对象都经过验证后才能保持这些对象可能更清晰。我不确定,还有其他人知道更好的实施吗?

1 个答案:

答案 0 :(得分:3)

我建议将论坛创建从控制器移动到模型。论坛将仅在成功创建上传时创建。

class Upload < ActiveRecord::Base
  ...
  has_one :forum
  after_create :create_forum
  ...
  def create_forum
    Forum.create(:upload_id => self.id, :title => self.name...)
  end
end


class Forum < ActiveRecord::Base
  ...
  has_many :posts
  after_create :create_first_post
  ...
  def create_first_post
    Post.new(:forum_id => self.id)
    # or self.posts << Post.new()
  end
end
相关问题