具有关系依赖的 Rails 事务

发布于 2024-11-05 03:36:24 字数 708 浏览 0 评论 0原文

我在 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'
app/controllers/projects_controller.rb:61:in
create'

Line 61 is Project.transaction do

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把时间冻结 2024-11-12 03:36:24

好吧,我自己想出来了。成员资格模型验证 :project_id 是否存在。在将项目保存到事务中之前,我正在设置membership.project。之后,我尝试保存成员资格,但由于项目是在数据库中创建之前设置的,因此 :project_id 为零。

为了修复此代码,我必须像这样重新排列它:

membership = Membership.new

Project.transaction do
  begin
    @project.save!
    membership.project = @project
    membership.save!
  rescue
    flash[:notice] = "There was an error creating your project."
  end
end

请注意,@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:

membership = Membership.new

Project.transaction do
  begin
    @project.save!
    membership.project = @project
    membership.save!
  rescue
    flash[:notice] = "There was an error creating your project."
  end
end

Note that the assignment of @project is now after the project has been saved (and an ID has been automatically generated).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文