首页 > 解决方案 > Mysql query rollbacks after beginning

问题描述

I'm taking a course on Lynda.com (Ruby on Rails 5 Essential Training). It is almost the same question as Can't insert MySQL query in Rails 5 (Lynda Course).

I have an issue with Many-to-Many association-Rich. The error comes when I write this line:

section = Section.create(:name => 'Section One', :position => 1)

Error is:

(0.3ms)  BEGIN
(0.3ms)  ROLLBACK
=> #<Section id: nil, page_id: nil, name: "Section One", position: 1, visible: false, content_type: nil, content: nil, created_at: nil, updated_at: nil>

I am following the course.

Migrate.rb looks like this:

class CreateSectionEdits < ActiveRecord::Migration[5.2]
  def up
    create_table :section_edits do |t|
      t.integer "admin_user_id"
      t.integer "section_id"
      t.string "summary"
      t.timestamps
    end
    add_index("section_edits", ["admin_user_id", "section_id"])
  end

  def down
    drop_table :section_edits
  end
end

Sectionedit.rb looks like this:

class SectionEdit < ApplicationRecord
  belongs_to :admin_users, optional: true  
  belongs_to :section
end

admin_user.rb looks like this:

class AdminUser < ApplicationRecord
  #self.table_name = "admin_users"
  has_and_belongs_to_many :pages
  has_many :section_edits
end

section.rb looks like this:

class Section < ApplicationRecord
  belongs_to :page, { :optional => false}
  has_many :section_edits
end

My error is not resolved. Please see. Looking for help.

标签: mysqlruby-on-rails

解决方案


在您的 Section 模型中,您写道belongs_to :page, { :optional => false},page不是可选的,因此您必须将 a 分配pagesection

你可以这样做:

page = Page.create(:field => 'something') # or page = Page.find(page_id), it depends on your app’s business logic
section = Section.create(:name => 'Section One', :position => 1, :page => page)

推荐阅读