1

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

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

儿童论坛:

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....

但我认为如果它们都经过验证,只保留对象可能会更干净。我不确定,还有其他人知道更好的实现吗?

4

1 回答 1

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
于 2012-07-06T02:40:24.257 回答