Откат запросов Mysql после начала - PullRequest
0 голосов
/ 22 октября 2018

Я прохожу курс на Lynda.com (обучение основам Ruby on Rails 5).Это почти тот же вопрос, что и Невозможно вставить запрос MySQL в Rails 5 (курс Lynda) .

У меня проблема с сопоставлением «многие ко многим».Ошибка появляется, когда я пишу эту строку:

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

Моя ошибка не устранена.Посмотри пожалуйста.Нужна помощь.

1 Ответ

0 голосов
/ 22 октября 2018

В модели вашего раздела вы написали 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...