无法在Rails 5中插入MySQL查询(Lynda课程)

问题描述 投票:1回答:2

我正在Lynda.com上学习一门课程(Ruby on Rails 5 Essential Training),我遇到了在桌面上添加记录的问题。这里有一些细节:目标是创建一个联合表,多对多关联,所以我们首先尝试使用我们想要在新表上使用的表创建记录。每次我写这行:

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

它给了我这个

    (0.2ms)  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> 

我检查了我的代码,一切似乎都很好。顺便插入其他表上的记录工作。这只是这张桌子。

重要的一点,这个表是以前创建的表。这是我们正在努力创造的新品。

我究竟做错了什么?

这是我的迁移代码:

class CreateSections < ActiveRecord::Migration[5.2]

  def up
    create_table :sections do |t|

      t.integer   "page_id"
      t.string    "name"
      t.integer   "position"
      t.boolean   "visible", :default => false
      t.string    "content_type"
      t.text      "content"
      t.timestamps
    end
    add_index("sections", "page_id")
  end

  def down
    drop_table :sections
  end


end

这是Section模型:

class Section < ApplicationRecord

belongs_to :page
has_many :section_edits


end
ruby-on-rails-5
2个回答
0
投票

错误是由以下原因导致的:belongs_to :page,因为page_id为零,默认情况下,Rails belongs_to帮助程序正在添加状态验证以确保关联有效。

要禁用此行为(在线验证),您可以使用:

belongs_to :page, optional: true

如上所述:https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to

或者您可以将page_id添加到您的Section.create电话中,如其他人所述:

page_id = 1 # or Page.first.id or any page id you need
section = Section.create(name: "Section One", position: 1, page_id: page_id)

0
投票

你的错误来自belongs_to :page 如果您尝试使用create!,您应该会看到以下错误消息:

ActiveRecord :: RecordInvalid:验证失败:页面必须存在

只需在您创建的部分中添加page_id

page_id = 1 # or Page.first.id or any page id you need
section = Section.create(name: "Section One", position: 1, page_id: page_id)
© www.soinside.com 2019 - 2024. All rights reserved.