Rails中的自我关联添加了外键错误

时间:2015-08-18 11:20:56

标签: ruby-on-rails

我在rails中做自我关联。我有Request模型,它应该引用自己。这就是我所拥有的:



class Request < ActiveRecord::Base

  has_many :sub_requests, class_name: 'Request',
                          foreign_key: 'parent_request_id'

  belongs_to :parent_request, class_name: 'Request'

end
&#13;
&#13;
&#13;

和我的迁移:

&#13;
&#13;
class CreateRequests < ActiveRecord::Migration
  def change
    create_table :requests do |t|
      t.references :parent_request, index: true
  
    end
  end
end
&#13;
&#13;
&#13;

但是我收到如下错误:

&#13;
&#13;
PG::UndefinedColumn: ERROR:  column requests.parent_request_id does not exist
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你运行rake db:migrate吗?如果你这样做,那就试试这个:

class Request < ActiveRecord::Base
  has_many :sub_requests, class_name: 'Request', foreign_key: 'parent_request_id', primary_key: 'id'
  belongs_to :parent_request, class_name: 'Request', foreign_key: 'parent_request_id', primary_key: 'id'
end

class CreateRequests < ActiveRecord::Migration
  def change
    create_table :requests do |t|
      t.integer :parent_request_id, index: true
    end
  end
end