我在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;
和我的迁移:
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.references :parent_request, index: true
end
end
end
&#13;
但是我收到如下错误:
PG::UndefinedColumn: ERROR: column requests.parent_request_id does not exist
&#13;
答案 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