保存时Rails回滚事务

时间:2017-12-10 22:33:38

标签: ruby-on-rails nested-forms

当我尝试保存@list

时,我在Lists_Controllers中的pry之后一直遇到“回滚事务”错误

我正在使用嵌套表单,当我撬开@ list.invites时,它显示invite.id为nil(但电子邮件在那里)。我想知道这是不是原因。

[3] pry(#<ListsController>)> @list.invites
=> [#<Invite:0x007f91de392e30
  id: nil,
  accepted: nil,
  exp_date: nil,
  email: "sldkfjsdf@email.com",
  invite_code: nil,
  list_id: nil,
  user_id: nil,
  created_at: nil,
  updated_at: nil>]

这是我的列表控制器

class ListsController < ApplicationController
before_action :authenticate_user!

  def new
    @list = List.new
    @list.invites.build
  end


  def create
    @list  = List.create(list_params)
    @list.users << current_user
    @list.admin_id = current_user.id
    binding.pry
    if @list.save
      redirect_to @list
    else
     render :new
    end
  end

  private

  def list_params
    params.require(:list).permit(:name, invites_attributes: [:email])
  end
 end

这是我的List.rb

class List < ApplicationRecord
has_many :lists_users
has_many :users, through: :lists_users
has_many :chores
has_many :invites

accepts_nested_attributes_for :invites , reject_if: proc { |attributes| 
attributes['email'].blank? }

validates :name, presence: true

end

和我的邀请.rb

class Invite < ApplicationRecord
  belongs_to :list
  belongs_to :user
end

我的名单和邀请表模式

create_table "invites", force: :cascade do |t|
    t.boolean "accepted"
    t.datetime "exp_date"
    t.string "email"
    t.string "invite_code"
    t.integer "list_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "lists", force: :cascade do |t|
    t.string "name"
    t.string "list_type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "admin_id"
  end

我的表格

<%= form_for(@list) do |f| %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %><br>
      Invites:
      <%= f.fields_for :invites do |invite| %>
        <%= invite.label :email %>
        <%= invite.text_field :email %>
      <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>

<% end %>

当我在pry

中尝试@ list.save时出现错误
pry(#<ListsController>)> @list.save
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

问题是我和用户和邀请之间的has_many和belongs_to关系。发送邀请时,如果系统中存在电子邮件,则为拥有该电子邮件的用户分配邀请。在列表创建时,如果邀请电子邮件不属于具有帐户的某人,则没有user_id分配给新邀请。我必须弄清楚我将如何做到这一点,但原始错误是固定的。

相关问题