每当我创建实体B
时,我都需要创建一个新实体A
。为此,我尝试在B.create
中的A.create
方法中添加对a_controller
的调用。但是这会出错:
Missing template a/create
所以我的问题是:如何从B
控制器创建实体A.create
?
答案 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/