Search code examples
ruby-on-railshas-one

Rails 4 has_one relation


I'm pretty new to Rails. I did the following migration:

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

And I have following models:

class Table < ActiveRecord::Base
belongs_to :user

belongs_to :order
end

class Order < ActiveRecord::Base
belongs_to :user

has_one :table
end

In console I have:

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

And I'm getting this error:

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

Any ideas?


Solution

  • If Order has one table then table needs the order's foreign key. So you actually run the opposite migrations. Table should have order_id foreign key.

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

    Then create a table record with order_id and call Order#table.