Reputation: 99
This is driving me BANANAS. I've tried the migration multiple ways, but the relationship only seems to go one way. I would like a relationship where I can Event.first.subjects << Subject.first
and Event.last.subjects << Subject.first
class Event < ApplicationRecord
has_and_belongs_to_many :subjects
end
class Subject < ApplicationRecord
has_and_belongs_to_many :events
end
I created a migration with
rails g migration CreateJoinTableEventSubject events subjects
class CreateJoinTableEventSubject < ActiveRecord::Migration[5.2]
def change
create_join_table :events, :subjects do |t|
t.index [:event_id, :subject_id]
t.index [:subject_id, :event_id]
end
end
end
I can Subject.first.events
which I don't need but Event.first.subjects
returns
ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: subjects.event_id: SELECT "subjects".* FROM "subjects" WHERE "subjects"."event_id" = ? LIMIT ?)
Here is the schema.rb
:
ActiveRecord::Schema.define(version: 2020_07_07_183602) do
create_table "events", force: :cascade do |t|
t.string "title"
t.text "description"
t.date "date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "events_subjects", id: false, force: :cascade do |t|
t.integer "event_id", null: false
t.integer "subject_id", null: false
t.index ["event_id", "subject_id"], name: "index_events_subjects_on_event_id_and_subject_id"
t.index ["subject_id", "event_id"], name: "index_events_subjects_on_subject_id_and_event_id"
end
create_table "subjects", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Upvotes: 0
Views: 278
Reputation: 99
So I had been clearing the DB by just deleting the development.sqlite3 file. When I actually ran rails db:drop
for this and ran the migrations it started working. I guess there's some artifact that was preserved without actually dropping the db?
Thanks to the commenters for making me think of this.
Upvotes: 1