GeekFitness GeekFitness - 1 year ago 54
Ruby Question

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

My models are

class Event < ApplicationRecord
has_many :event_options

class EventOption < ApplicationRecord
belongs_to :event

rails c
, I can use this to create an
just fine.

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

However, when I do this:

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

It gives me a rollback with the error:

@messages={:event=>["must exist"]}>

I try it with
and just
as well (as well as
:event_id/:event/:id => 1
and , but for some reason, none of them let me provide a link to the
to the
on creation.

Any clue?

Answer Source

I have a feeling that you haven't properly associated the database columns. In that case, you need to create a migration:

rails g migration AddForeignKeyToEventOptions

And then in the migration file you'll need to add a field for the event_id:

def change
  add_column :event_options, :event_id, :integer

Then you'll need to run your migrations:

rake db:migrate

Once these are properly associated you'll need to restart your console and then try associating your event_option with any event:

  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.

EDIT: Here's a link to the rails docs on creating migrations:

I'm looking at this section:

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
  def change
    add_reference :products, :user, foreign_key: true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download