.create 和 .save 上的条目回滚,因为 foreign_key "must exist",但不会接受值

Entry rollback on .create and .save because foreign_key "must exist", but won't accept a value

我的模特是

class Event < ApplicationRecord
  has_many :event_options
end

class EventOption < ApplicationRecord
  belongs_to :event
end

rails c中,我可以用它来创建一个Event就好了。

Event.create(name:"Face Painting", active:true)

但是,当我这样做时:

EventOption.create(description:"You give us money. We paint your face.", price: 250.00, name: "People Painting 1", event: 1);

它给了我一个错误的回滚:

 @details={:event=>[{:error=>:blank}]},
 @messages={:event=>["must exist"]}>

我尝试使用 event_idid(以及 :event_id/:event/:id => 1 和 ,但出于某种原因,其中的 none 让我提供了一个link 到 EventOptionEvent 创建时。

有线索吗?

怎么样:

event = Event.create(name:"Face Painting", active:true)

EventOption.create( description: "You give us money. We paint your face.", price: 250.00, name: "People Painting 1", event: event )

此外,除非您将两个语句组合在一行中,否则 Ruby 中不需要分号。

我感觉您没有正确关联数据库列。在这种情况下,您需要创建迁移:

rails g migration AddForeignKeyToEventOptions

然后在迁移文件中,您需要为 event_id 添加一个字段:

...
def change
  add_column :event_options, :event_id, :integer
end
...

然后你需要运行你的迁移:

rake db:migrate

一旦这些正确关联,您将需要重新启动控制台,然后尝试将您的 event_option 与任何事件相关联:

EventOption.create(
  description:"You give us money. We paint your face.",
  price: 250.00,
  name: "People Painting 1",
  event: 1     # Supposing that event with id: 1 exists.
)

编辑: 这是关于创建迁移的 rails 文档的 link: http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration

我正在查看这个部分:

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
  def change
    add_reference :products, :user, foreign_key: true
 end
end