0

B每当我创建一个实体时,我都需要创建一个新实体A。为此,我尝试B.createA.create. a_controller然而,这给出了一个错误:

Missing template a/create

所以我的问题是:如何BA.create控制器创建实体?

4

1 回答 1

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/

于 2012-07-15T17:20:21.730 回答