Can't insert MySQL query in Rails 5 (Lynda Course)

拟墨画扇 提交于 2019-12-13 18:09:32

问题


I'm taking a course on Lynda.com (Ruby on Rails 5 Essential Training) and I'm having an issue with adding a record on a table. Here's some details: The objective is to create a joint table, Many-to-Many association, so we're first trying to create a record on with of the tables we want to use on the new table. And everytime I write this line:

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

It gives me this

    (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> 

I checked my code and everything seems fine. By the way inserting records on other tables works. It's just this table.

one important point, This table is a previously created table. It's the new one we're trying to create.

What am I doing wrong?

Here is my code from migrate:

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

Here is the Section model:

class Section < ApplicationRecord

belongs_to :page
has_many :section_edits


end

回答1:


The error is caused by: belongs_to :page as the page_id is nil and by default Rails belongs_to helper is adding a presence validation to make sure that the association is valid.

To disable this behaviour (presence validation) you can use:

belongs_to :page, optional: true

as mentioned here: https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to

or you can add page_id to your Section.create call as mentioned by others:

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)



回答2:


Your error comes from belongs_to :page
If you try with create!, you should see this error message:

ActiveRecord::RecordInvalid: Validation failed: Page must exist

Just add page_id in your section creation:

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)


来源:https://stackoverflow.com/questions/52078024/cant-insert-mysql-query-in-rails-5-lynda-course

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!