首页 > 解决方案 > 使用 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

并调整了参数的权限。

标签: ruby-on-railsrubyhas-manybelongs-tocollection-select

解决方案


你的代码对我来说看起来不太好。我会改变它:

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。

如果您发布完整的控制器代码,将更容易提供更多帮助。


推荐阅读