【问题标题】:Needing the same ID for two different entries in one tablerow一个表行中的两个不同条目需要相同的 ID
【发布时间】:2016-03-11 18:04:53
【问题描述】:

我构建了一个解决铁路优化问题的应用。您可以创建一些车站,您需要创建一个包含列车号、到达站、到达时间、出发站、出发时间和此铁路连接需求的时间表。现在我遇到了问题,我只有一个用于出发站的 station_id,但我的到达站也需要 station_id。这是必不可少的,因为当我删除一个车站时,我希望使用该车站的相应铁路连接也被删除。这是我的 schema.rb 的一小段摘录:

ActiveRecord::Schema.define(version: 20160310101628) do

create_table "stations", force: :cascade do |t|
t.string   "shortcut"
t.string   "name"
t.datetime "created_at",         null: false
t.datetime "updated_at",         null: false
end

create_table "timetables", force: :cascade do |t|
t.integer  "train_number"
t.string   "departure_station"
t.string   "departure_time"
t.string   "arrival_station"
t.string   "arrival_time"
t.integer  "demand_first_class"
t.integer  "demand_second_class"
t.datetime "created_at",          null: false
t.datetime "updated_at",          null: false
t.integer  "station_id"
end

end

创建新站时是否有创建命令,例如一个 station_departure_id 总是与 station_id 具有相同的 ID 号? 是否有其他可能解决此问题?

【问题讨论】:

  • 发布相应的模型会更有意义。

标签: sql ruby-on-rails ruby


【解决方案1】:

好的,如果我理解正确的话:

您希望每个Timetable 都有出发站和到达站,并确保在删除Station 时,任何以Station 作为出发站或到达站的Timetables也被删除了。

您可以通过以下方式实现此目的:

class Timetable < ActiveRecord::Base
  belongs_to :departure_station, class: 'Station', foreign_key: :departure_station_id
  belongs_to :arrival_station, class: 'Station', foreign_key: :arrival_station_id

  # ...
end
class Station < ActiveRecord::Base
  has_many :departure_timetables, class: 'Timetable', foreign_key: :departure_station_id, dependent: :destroy
  has_many :arrival_timetables, class: 'Timetable', foreign_key: :arrival_station_id, dependent: :destroy

  #...
end

has_many 类中has_many 关联上的dependent: :destroy 选项可确保将该站作为任一出发站到达站的任何TimetableStation被删除时,站将被删除。

【讨论】:

  • 解决方案不起作用 - 我想是因为我的车站表中没有离开站和到达站,分别没有单独的出发站和到达站表。优化问题是一个循环铁路问题,所以创建的每个车站必须至少有一次出发站和至少一次到达站!这就是为什么我只建了一个车站表和一个时间表站。我已经更新了我的第一篇文章,因此您可以看到两个表格“车站”和“时间表”及其条目。我希望我描述的问题相当容易理解..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 2016-03-07
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多