在.create和.save上进行回滚,因为foreign_key“必须存在”,但不接受值

时间:2016-08-14 18:54:07

标签: ruby-on-rails ruby activerecord console ruby-on-rails-5

我的模特

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进行尝试,但由于某些原因,他们都没有让我提供{{1}的链接创建时EventOption

有任何线索吗?

2 个答案:

答案 0 :(得分:2)

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

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文档的链接: 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

答案 1 :(得分:0)

怎么样:

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中不需要分号。