【发布时间】:2018-10-04 08:47:51
【问题描述】:
我有以下简化模型,以及使用 Sqlite 的 rails 项目中的控制器中的一个动作。
在我添加车库模型之前,汽车控制器中的更新操作运行良好。由于garage 有很多车,而cars 有一个车库,所以我在迁移中指定了一个外键关系,在cars 表中使用garage_id。
在模型中添加“has_many :cars”和“belongs_to:garage”关系后,cars#update 操作因“404 回滚事务”错误而停止工作。关联似乎有些问题。
如何指定模型之间的正确关系?
class Garage < ApplicationRecord
has_many :cars
end
class User < ApplicationRecord
has_many :cars
end
class Car < ApplicationRecord
# car table has building_id as foreign key
belongs_to :garage
belongs_to :user
has_one :option
end
class Option < ApplicationRecord
# option table has car_id as foreign key
belongs_to :car
end
class CarsController < ApplicationController
def update
@car.update(params[:color])
@option.update(params[:seat])
# getting "404 rolling back transaction" error.
end
end
【问题讨论】:
-
试试
belongs_to: garage, optional: true。 -
太棒了!有效。非常感谢。
-
我真的无法理解那些在没有给出一些正当理由的情况下对合法问题投反对票的人的心态。
标签: ruby-on-rails sqlite activerecord