GeekFitness GeekFitness - 3 months ago 5
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
end

class EventOption < ApplicationRecord
belongs_to :event
end


In
rails c
, I can use this to create an
Event
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:

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


I try it with
event_id
and just
id
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
EventOption
to the
Event
on creation.

Any clue?

Answer

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
end
...

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:

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.
)

EDIT: Here's a link to the rails docs on creating migrations: http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration

I'm looking at this section:

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