Rails 4 has_one关系

时间:2015-07-05 17:24:53

标签: ruby-on-rails has-one

我对Rails很陌生。我做了以下迁移:

def change
  add_reference   :orders, :table, index: true
  add_foreign_key :orders, :tables
end

我有以下模特:

class Table < ActiveRecord::Base
belongs_to :user

belongs_to :order
end

class Order < ActiveRecord::Base
belongs_to :user

has_one :table
end

在控制台中我有:

 o = Order.new
 o.name = "pippo"
 o.user_id = 4
 o.table_id=Table.first.id
 o.save
 o.table

我收到了这个错误:

PG::UndefinedColumn: ERROR:  column tables.order_id does not exist
LINE 1: SELECT  "tables".* FROM "tables" WHERE "tables"."order_id" =...

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果Order有一个表,那么表需要订单的外键。所以你实际上运行了相反的迁移。表应该有order_id外键。

data.frame(col11 = c(df1,recursive=TRUE))
      col11
col11   1
col12   2
col13   3
col21   4
col22   5
col23   6
col31   7
col32   8
col33   9

然后使用order_id创建一个表记录并调用Order#table。