创建关联对象 - Rails 4.2

时间:2015-03-22 23:53:26

标签: ruby-on-rails postgresql ruby-on-rails-4

我正在尝试在我的Rails 4应用程序中创建一些简单的关系。我有三个模型:用户,列表,单词。

这是一个简单的“列表”应用程序,每个用户都有通过列表的单词。

我目前有以下协会......

用户模型

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

列表模型

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

Word模型

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

创建对象:

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

# Display words in list
> list.words

上述关联对象给出错误:PG :: UndefinedColumn:ERROR:列words.list_id不存在。

我也尝试使用Foreigner gem创建具有外键约束的迁移,但仍然遇到错误。请帮忙!

1 个答案:

答案 0 :(得分:3)

根据错误告诉,list_id列不存在, 你的迁移应该看起来像这样

 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

然后在创建记录时:

> 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