使用一个controller.create创建2个不同的实体

时间:2012-07-15 17:07:55

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

每当我创建实体B时,我都需要创建一个新实体A。为此,我尝试在B.create中的A.create方法中添加对a_controller的调用。但是这会出错:

Missing template a/create

所以我的问题是:如何从B控制器创建实体A.create

1 个答案:

答案 0 :(得分:2)

这样的事情?

def create
  @A = A.new(params[:a])
  @B = B.new(params[:b])

  respond_to do |format|
    if @A.save && @B.save
      format.html { redirect_to @A, :notice => 'A was successfully created.' }        
    else
      # render new with validation errors
      format.html { render :action => "new" }        
    end
  end
end

但是如果您的对象是“相关的”,即has_many或belongs_to,那么您可能需要类似

的内容
# project has_many tasks
def create
  @project = Project.new(params[:project])
  @project.tasks.new(params[:task])
  if @project.save # this should save both objects and in the same transaction
    ....
end

和第三个选项是使用accepts_nested_attributes_for - 请在此处阅读更多内容:http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/