mysql - 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.
解决方案
在您的 Section 模型中,您写道belongs_to :page, { :optional => false}
,page
不是可选的,因此您必须将 a 分配page
给section
你可以这样做:
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)
推荐阅读
- python - 如何在 Databricks 中按计划运行 Spark (python) ETL 管道
- python - Beautifulsoup 如何选择所有的“a”标签
- python - 有没有办法让我检查两个列表是否共享一个公共元素/条目,然后将该共享元素声明为变量?
- java - Apache Poi RowIterator 仅返回最后 100 (0 - 99) 行
- python - 为 pandas 中的特定行设置数据类型
- node.js - Nodejs HTTP 请求正文值控制台日志
- python-3.x - 有没有办法从 Pytube 获取流的 URL?
- python - 我需要帮助字符串格式化
- javascript - 在 keydown 上从数组中返回非重复的随机项
- python - TensorFlow 忽略了 RTX 3000 系列 GPU