我正在Lynda.com上学习一门课程(Ruby on Rails 5基本培训)。这和Can't insert MySQL query in Rails 5 (Lynda Course)几乎是相同的问题。
我与Rich-to-Many关联有问题。当我写此行时出现错误:
section = Section.create(:name => 'Section One', :position => 1)
错误是:
(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>
我正在学习这门课程。
Migrate.rb看起来像这样:
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看起来像这样:
class SectionEdit < ApplicationRecord
belongs_to :admin_users, optional: true
belongs_to :section
end
admin_user.rb看起来像这样:
class AdminUser < ApplicationRecord
#self.table_name = "admin_users"
has_and_belongs_to_many :pages
has_many :section_edits
end
section.rb看起来像这样:
class Section < ApplicationRecord
belongs_to :page, { :optional => false}
has_many :section_edits
end
我的错误无法解决。请参阅。寻找帮助。
答案 0 :(得分:0)
在您的Section模型中,您写了belongs_to :page, { :optional => false}
,page
不是可选的,因此您必须为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)