ruby-on-rails - 使用 collection_select 通过 has_many 和 belongs_to 关联在预订中保存两个类的 ID 保存时会抛出错误“必须存在”
问题描述
我正在为学习轨道构建一个简单的预订应用程序。我为人、汽车和预订搭建脚手架。
现在,当我尝试创建预订时,我得到
2 个错误导致此预订无法保存:
- 人必须存在
- 汽车必须存在
代码
car.rb
class Car < ApplicationRecord
has_many :bookings
def brand_with_licence_plate
"#{brand} #{licence_plate}"
end
end
person.rb
class Person < ApplicationRecord
has_many :bookings
def complete_name
"#{first_name} #{last_name}"
end
end
bookings.rb
class Booking < ApplicationRecord
belongs_to :Person
belongs_to :Car
end
我添加了 ID 列,如下所示:
class AddItemsToBookings < ActiveRecord::Migration[6.1]
def self.up
add_column :bookings, :car_id, :integer
add_column :bookings, :person_id, :integer
end
end
我添加到以下_form.html.erb
<div class="field">
<%= form.label :Person %>
<%= form.collection_select(:person_id, Person.all, :id, :complete_name) %>
</div>
<div class="field">
<%= form.label :Car %>
<%= form.select :car_id, options_from_collection_for_select(Car.all, 'id','brand_with_licence_plate') %>
</div>
并添加到bookings_controller.rb
def booking_params
params.require(:booking).permit(:start, :end, :person_id, :car_id)
end
我看过这里并尝试更改<%= form.select :car_id, options_from_collection_for_select(Car.all, 'id', 'brand_with_licence_plate') %>
为一个答案中所述,但给了我同样的错误。
当我查看文档时,一切似乎都很好。
似乎在这里缺少一些基本的东西。任何如何解决这个问题的想法都值得赞赏。
更新:
我删除了整数 id 列并运行了新的迁移
class AddReferencesToBookingForPersonAndCar < ActiveRecord::Migration[6.1]
def change
add_reference :bookings, :people, foreign_key: true
add_reference :bookings, :cars, foreign_key: true
end
end
并调整了参数的权限。
解决方案
你的代码对我来说看起来不太好。我会改变它:
class Booking < ApplicationRecord
belongs_to :person
belongs_to :car
end
主要是person和car都是小写。另外,我注意到在您的迁移中,您以复数形式创建汽车。它应该是:
class AddReferencesToBookingForPersonAndCar < ActiveRecord::Migration[6.1]
def change
add_reference :bookings, :person, foreign_key: true
add_reference :bookings, :car, foreign_key: true
end
end
belongs_to :car 需要一个 car_id 并且看起来迁移正在创建一个 cars_id。
如果您发布完整的控制器代码,将更容易提供更多帮助。
推荐阅读
- powershell - 使用 POWERSHELL 检查用户是否具有对目标文件夹的 WRITE 访问权限
- sql - 单个 TSQL 请求上的 RID 死锁
- java - 将微秒级添加到 log4j
- http - 实现一个能够为网站提供服务的 MQTT 服务器
- php - PHP我如何在IIS10上使用ServerPush HTTP2
- c# - Visual C#中具有相同列的多个DataTable
- context-free-grammar - L = { a^nb^nc^md^m : n >= 1, m >= 1 } U { a^nb^mc^md^n : n >= 1, m >= 1 } 是正则吗?
- python - 如何在 python 中使用 evdev 从隐藏设备(条形码扫描仪)获取有效的可理解字符串
- python - 如何复制包含列表的 pandas 数据框,以便将来对副本中列表的更改不会改变原始列表
- html - 连接api时出现ionic 3 HttpClient错误,“对象”类型上不存在属性“json”