The Whiz of Oz
The Whiz of Oz

Reputation: 7043

Rails relation throws an error: SQLException: no such column

I have events, which have speakers and sliders.

class Event

  has_many :speakers, dependent: :destroy
  accepts_nested_attributes_for :speakers, allow_destroy: true

  has_many :sliders, dependent: :destroy

class Speaker

 belongs_to :event

class Slider

 belongs_to :event

Speakers do not have their own controller (they are submitted straight to model via nested attributes), sliders do.

When I upload new sliders, I get an error when trying to output them in the event view (the speakers show up nicely):

Event view

<% @event.sliders.each do %>
  <p>hello dolly</p>
<% end %>

Error

SQLite3::SQLException: no such column: sliders.event_id: SELECT "sliders".* FROM "sliders"  WHERE "sliders"."event_id" = ?

Event controller

  def show      
    @event = Event.find(params[:id])
  end

Console:

>> e = Event.find_by(id:9)
=> #<Event id: 9, title: "...">

>> e.speakers
=> #<ActiveRecord::Associations::CollectionProxy [#<Speaker id: 59, name: "...", created_at: "2013-08-27 09:28:58", updated_at: "2013-08-27 09:28:58", event_id: 9>]>

>> e.sliders
!! #<ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: sliders.event_id: SELECT "sliders".* FROM "sliders"  WHERE "sliders"."event_id" = ?>

My migrations & schemas are all in place, I guess I'm having troubles with relations?

Thank you Stackoverflow people

Upvotes: 3

Views: 2073

Answers (2)

Rajarshi Das
Rajarshi Das

Reputation: 12340

is yours sliders table has event_id column or any foreign_key ... add it by generating a migration

rails generate migration AddEventIdToSliders event_id:integer

rake db:migrate

thanks

Upvotes: 4

vee
vee

Reputation: 38645

Your sliders table is missing event_id column which is why you are getting that error. You can run another migration to add event_id column to sliders table using the following:

rails g migration add_event_id_to_sliders event_id:integer

Then run the migration:

rake db:migrate

Upvotes: 4

Related Questions