ActiveRecord:dependent => :删除错误的id属性

时间:2016-05-04 18:01:54

标签: ruby-on-rails activerecord

我有一个Step类,可以是原点,步骤或目的地,具体取决于model。还有一个Route类,它包含一个起点和目的地,如下:

class Route < ActiveRecord::Base
  has_one :origin, -> {where(model: "origin")}, class_name: "Step", :foreign_key => "origin_id", :dependent => :delete
  has_one :destination, -> {where(model: "destination")}, class_name: "Step", :foreign_key => "destination_id", :dependent => :delete

我想在销毁路线时删除链接的步骤,但我收到此错误:ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: steps.origin_id

如何向AR解释必须找到steps.id而不是steps.origin_id

这是我的架构。

create_table "steps", force: :cascade do |t|
    t.string   "model"
    t.float    "lat"
    t.float    "lng"
    t.text     "formatted_address"
    t.string   "vicinity"
    t.string   "name"
    t.integer  "distance"
    t.integer  "duration"
    t.integer  "tour_id"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

  add_index "steps", ["tour_id"], name: "index_steps_on_tour_id"

  create_table "routes", force: :cascade do |t|
    t.integer  "origin_id"
    t.integer  "destination_id"
    t.integer  "user_id"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
  end

  add_index "routes", ["user_id"], name: "index_routes_on_user_id"

1 个答案:

答案 0 :(得分:1)

结果证明这是以相反方式定义的关联的问题。

在Rails下,约定如下:模型表包含外键,使用IOError: [Errno 2] No such file or directory: 'N:\\MMS Managers\\house_opportunities.csv' 作为关联。其他模型在其表中没有外键,使用belongs_tohas_one等进行关联。

因此,在这种情况下,has_many中的关联应如下所示:

Route

有关详细信息,请参阅Rails指南中的this chapter