0

I'm trying to create a few simple relations in my Rails 4 application. I have three models: user, list, word.

This is for a simple 'list' application, where each user has_many words through lists.

I currently have the following associations...

User model

class User < ActiveRecord::Base
  has_many :lists
  has_many :words, through: :lists
end

List model

class List < ActiveRecord::Base
  has_many :words
  belongs_to :user
end

Word model

class Word < ActiveRecord::Base
  belongs_to :list
end

DB Scheme

ActiveRecord::Schema.define(version: 20150320200247) do

# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

create_table "users", force: :cascade do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

create_table "lists", force: :cascade do |t|
  t.string   "name"
  t.text     "description"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

create_table "words", force: :cascade do |t|
  t.string   "word"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end
  add_index "words", ["word"], name: "index_words_on_word", using: :btree

end

creating objects:

> user = User.create(name: "Kyle")
> list = List.create(name: "List One")
> word = Word.create(word: "StackOverflow")

# Display words in list
> list.words

The above association object gives an error: PG::UndefinedColumn: ERROR: column words.list_id does not exist.

I've also tried creating migrations with foreign key constraints using the Foreigner gem, but am still getting errors. Please help!

2
  • Show your schema.rb file Commented Mar 23, 2015 at 0:13
  • your are missing list_id in your words table and user_id in the lists table, these are required for the association to work correctly. Commented Mar 23, 2015 at 0:58

1 Answer 1

3

From what the error tells, the list_id column is not present, your migration should look something like this

 class CreateWords < ActiveRecord::Migration
  def change
    create_table :words do |t|
      t.string :word
      t.integer :list_id

      t.timestamps null: false
    end
  end
end

then when creating your records:

> user = User.create(name: "Kyle")
> list =  List.create(name: "List One", user_id: user.id)
> word = Word.create(word: "StackOverflow", list_id: list.id)

# Should work
> list.words
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.