具有关系依赖的 Rails 事务
我在 Rails 3 中的事务处理方面遇到了一些麻烦。基本上我有两个模型(项目和会员资格)
@project = Project.new(params[:project])
@project.user = current_user
membership = Membership.new
membership.project = @project
Project.transaction do
begin
@project.save!
membership.save!
rescue
flash[:notice] = "There was an error creating your project."
end
end
我正在创建一个新项目并尝试立即为该项目创建会员资格(会员资格实际上也与用户有关系)型号,n:m)。
现在我正在启动一个事务来保存项目和事务中的成员资格。问题是我遇到了异常:
验证失败:项目不能为空
app/controllers/projects_controller.rb:64:in
block in create'
创建'
app/controllers/projects_controller.rb:61:in
第 61 行是 Project.transaction do
I'm having some trouble with transactions in Rails 3. Basically I have two models (Project and Membership)
@project = Project.new(params[:project])
@project.user = current_user
membership = Membership.new
membership.project = @project
Project.transaction do
begin
@project.save!
membership.save!
rescue
flash[:notice] = "There was an error creating your project."
end
end
I am creating a new project and trying to immediately create a membership for the project (membership does actually also have a relation to the a User model, n:m).
Now I'm starting a transaction to save the project and the membership inside the transaction. Problem is that I'm getting an exception:
Validation failed: Project can't be blank
app/controllers/projects_controller.rb:64:in
block in create'
create'
app/controllers/projects_controller.rb:61:in
Line 61 is Project.transaction do
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我自己想出来了。成员资格模型验证 :project_id 是否存在。在将项目保存到事务中之前,我正在设置membership.project。之后,我尝试保存成员资格,但由于项目是在数据库中创建之前设置的,因此 :project_id 为零。
为了修复此代码,我必须像这样重新排列它:
请注意,
@project
的分配现在是在项目保存后之后(并且 ID 已自动生成)生成)。OK I figured it out myself. The Membership model validates the presence of :project_id. I am setting membership.project before I save the project inside the transaction. After that I am trying to save the membership, but as the project was set before it was created in the database the :project_id is nil.
In order to fix this code I had to rearrange it like this:
Note that the assignment of
@project
is now after the project has been saved (and an ID has been automatically generated).